Sunday, March 27, 2011

Data URL / PNG from UIImage

Hello, 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.

From stackoverflow
  • 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

  • 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 *dataForPNGFile = 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.

    rpetrich : You may not want to use the base64+javascript method for large images as is uses a lot of memory--Safari will keep both the base64 and decoded versions loaded. Should work well for small images or if you only have a few large ones

0 comments:

Post a Comment