Using a UIImage directly in your UIWebView

If you have a UIImage that you need to put into a UIWebView, you have a couple choices on how to go about the task.

(Note that when I say UIImage, I mean a reference to a UIImage.  Not an NSString with the name of the image, but the image itself.)

Option 1

Write the UIImage out to the filesystem with a unique name and then reference that name in the HTML that you load into the UIWebView.  After the UIWebView loads, delete the file from the file system.

This is OK but may introduce a performance penalty in writing out to the file system and it requires additional code to create a unique filename, get a reference to the documents/temp/other directory into which to write the file and construct the base URL to that filesystem location.    The performance penalty is likely to go unnoticed, but this does introduce additional code (read: maintenance overhead) that can be minimized if you opt for Option 2.

Option 2

Encode the images data to base64 and use it inline in the HTML loaded into the UIWebView.   Encoding the image to base64 doesn’t come natively in the UIImage class.  You will need a base64 NSData category that you can find here.  (I use the one posted by MiloBird as it doesn’t require libcrypto and he’s offered it up as public domain)

- (NSString *) htmlForPNGImage:(UIImage *) image {
    NSData *imageData = UIImagePNGRepresentation(image);
    NSString *imageSource = [NSString stringWithFormat:@"data:image/png;base64,%@",[imageData base64Encoding]];
    return [NSString stringWithFormat:"<img src='%@' />", imageSource];

Note that the code sample above will only work for a PNG image.  There is a corresponding UIImageJPEGRepresentation function as well.

Granted this does introduce the NSData category and with it considerably more source code (and a certain amount of trust in the development community) than Option 1, but I do like the simplicity of the overall code.

Leave a Reply