Isaac Waller
Isaac Waller

Reputation: 32740

Data URL / PNG from UIImage

I have a iPhone program that has a UIImage. This UIImage needs to be transferred to a javascript Image object in a UIWebView. I was thinking this could be done by using a data url I send to the UIWebView like this:

[wview stringByEvaluatingJavaScriptFromString:@"loadimage('%d')",dataurlfromuiimage];

So, I need to transfer my UIImage into a Data: URL. I could do this myself if I can just get the PNG data, but I cannot find how do do that either. If there is a better way to send this to the WebView, that would be good also.

Upvotes: 5

Views: 10862

Answers (2)

Brad Larson
Brad Larson

Reputation: 170317

To get an NSData representation of your image in the PNG format, use

NSData *dataForPNGFile = UIImagePNGRepresentation(yourImage);

Likewise, a JPEG representation can be obtained using

NSData *dataForJPEGFile = UIImageJPEGRepresentation(yourImage, 0.9f);

Once you have the NSData, you could write it to your Documents directory using writeToFile:atomically:, and then I believe you can pass it in as a local URL (although I've not tried this). An alternative is to use the Base64 NSData category that François P. references and somehow send it to JavaScript as Base64.

Upvotes: 22

François P.
François P.

Reputation: 5166

Unfortunately, you'll need to convert your UIImage to the a file representation of your image, not the decoded pixels information that is stored in the UIImage structure. That is, you'll need to somehow write it to a temporary file and get the raw NSData bytes for the file (probably JPEG ou PNG). Then use a BASE64 encoder. I don't think it is already provided by Apple, so might you wanna look at this article: http://www.cocoadev.com/index.pl?BaseSixtyFour

Upvotes: 0

Related Questions