Wednesday, June 18, 2014

uiimage to nsdata to nsstring to nsdata to uiimage

Why would you want to make these conversions?

nsstring is a format that can be sent to any system.  In my case I want to send it to an SQLite database.  However, SQLite does not support images.  the closest thing to it is a blob type.  A blog type accepts a bunch of bytes.  While this is good, it might not always suit your purposes.

If you do not want to use a blob type, you can use the text type.  In the following blog post I will detail how to convert an uiimage to nsdata to nsstring.  Then how to turn that nsstring back to data then back to uiimage.


UIImage *originalImage = ...; //get image from somewhere.  a path or an iphoto library.

NSData *originalData = UIImagePNGRepresentation(originalImage);

NSString *originalString = [originalData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];

//Now that you have the data in a string format you can pass it around.  In my case I stored it in my SQLite database.  Now if I want to retrieve it I need to convert it back.

NSData *decodedData = [[NSData alloc] initWithBase64EncodedString:originalString options:NSDataBase64DecodingIgnoreUnknownCharacters];

UIImage *decodedImage = [UIImage imageWithData:decodedData];

-------------------
There is only one decoder option: "NSDataBase64DecodingIgnoreUnknownCharacters"
But there are four encoder options.  In the example above I used "NSDataBase64Encoding64CharacterLineLength"

but there are 3 others.  What are the differences and why would you use them?


  • NSDataBase64Encoding64CharacterLineLength
    • Sets the maximum line length to 64 characters, after which a line ending is inserted.
  • NSDataBase64Encoding76CharacterLineLength
    • Sets the maximum line Length to 76 characters, after which a line ending is inserted.
  • NSDataBase64EncodingEndLineWithCarriageReturn
    • When a maximum line length is set, specify that the line ending to insert should include a carriage return
  • NSDataBase64EncodingEndLineWithLineFeed
    • When a maximum line length is set, specify that the line ending to insert should include a line feed.

No comments:

Post a Comment