Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Data URL / PNG from UIImage

Tags:

cocoa-touch

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.

like image 831
Isaac Waller Avatar asked Feb 01 '09 22:02

Isaac Waller


1 Answers

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.

like image 161
Brad Larson Avatar answered Oct 04 '22 10:10

Brad Larson