UIImage from bytes held in NSString

好久不见. 提交于 2019-12-03 10:14:41

问题


I am trying to create a UIImage from a byte array that is actually held within a NSString.

Can someone please tell me how I can do that?

Here is what I was thinking of doing:

NSString *sourceString = @"mYActualBytesAREinHERe=";
//get the bytes
const char *bytesArray = [sourceString cStringUsingEncoding:NSASCIIStringEncoding];
//build the NSData object
NSData *data = [NSData dataWithBytes:bytesArray length:[sourceString length]];
//create actual image
UIImage *image = [UIImage imageWithData:data];

The problem is image is always 0x0 (nil).

Any suggestions would be appreciated.

Thanks!


回答1:


To convert an image to string you need a method to convert NSData to a base64Encoded string and back (lots of examples here). The easiest ones to use are categories on NSData so you can do something like this:

UIImage* pic = [UIImage imageNamed:@"sample.png"];
NSData* pictureData = UIImagePNGRepresentation(pic);
NSString* pictureDataString = [pictureData base64Encoding];

To go the other way you need a reverse converter:

UIImage* image = [UIImage imageWithData:[NSData 
            dataFromBase64EncodedString: pictureDataString]];



回答2:


[UIImage imageWithData:data]; will return nil if it doesn't understand the data being passed to it. I would double check your encoding, etc. It's odd that a binary string would hold pure image data without some kind of encoding (base64, etc.). String encodings and binary encodings aren't compatible.




回答3:


I bet your image data has some null characters in there (0x00) and as you know that is the terminator for the string, so when you ask for the C string, you probably get way-way too little data.

Try something like - (NSData *)dataUsingEncoding:(NSStringEncoding)encoding; to generate your NSData.

If that doesn't work you need to evaluate whether the setting the data into an NSString (with embedded null chars) isn't causing a loss of data too.

Like one of the other respondents, perhaps base-64 encoding your data would be a good idea (if using a string to transport the img data is a requirement)

Good luck.



来源:https://stackoverflow.com/questions/1101002/uiimage-from-bytes-held-in-nsstring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!