iosios6uiimageuikitdata-url

Converting a UIImage into a data URI


Suppose I have a UIImage instance that I would like to convert into a data URI and inject into a UIWebView.

I know I can convert the UIImage to PNG/JPEG NSData using PNGRepresentation/JPEGRepresentation methods. But then how do I make sure that the conversion is base64? And then how do I create a string with the actual URI and headers present?


Solution

  • Creating NSData out of it won't encode in base 64. NSData a binary data (bytes, in the range 0-255); base 64 encoding is a text encoding that uses a subset of ASCII to represent byte values. What you'll want to do is create the NSData, then use a conversion routine to encode it into a base 64 string; there's lots of references for doing that. Once you have the base64 string, use the standard methodology for inserting image data into HTML.