Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIImage from bytes held in NSString

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!

like image 392
nicktmro Avatar asked Dec 14 '22 03:12

nicktmro


1 Answers

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]];
like image 135
Ramin Avatar answered Dec 23 '22 22:12

Ramin