开发者

display images in <img> tag using nsdata

is this possible? my app will download a zip file from the server and I save all the images in an array like this:

    ZipReadStream *read = [unzipFile readCurrentFileIn开发者_如何学运维Zip];
    NSMutableData *data = [[NSMutableData alloc] initWithLength:info.length];
    int bytesRead= [read readDataWithBuffer:data];

    if(bytesRead > 0)
    {
     [imagesData addObject:data];
     [imagesName addObject:info.name];
    }

then I filter w/c images to be displayed inside the uiview and w/c images to be displayed inside the uiwebview. I display the images inside the uiview like this:

    UIImage *imageForThisQuestion = [[UIImage alloc]initWithData:[imagesData       
    objectAtIndex:indexOfThisImage]];

this works fine inside the uiview. but how do I display the some of the images inside the uiwebview? can I use the tag here? and also my uiwebview might appear in this format:

    "blah blah blah blah <img src...> blah blah blah <img src...>"


You don't want to save an image in file to refer on it in html like < img src="myimage.png">, right? You can use data URI scheme to encode your image into URI, and use img tag like

< img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO 9TXL0Y4OHwAAAABJRU5ErkJggg==" >

Read hear how to base64 encode NSData of your image.


For anyone wanting a quick and clear answer and slip reading the whole article supplied above, this is the code you want to use:

NSString* imgInBase64 = [imageObject base64EncodedStringWithOptions:0];
NSString* imgSrcValue = [@"data:image/png;base64," stringByAppendingString:imgInBase64]

and you inject that string to any <img src="{{imgSrcValue}}"> element. Notice the 0 value to the base64EncodedStringWithOptions which may help you avoid crashes with images which produce huge Base64 strings. Also you can change the png to any supported image format


You have to load the HTML code with the correct baseURL:

NSString *path = [[NSBundle mainBundle] bundlePath];
NSURL *baseURL = [NSURL fileURLWithPath:path];
[webView loadHTMLString:htmlString baseURL:baseURL];

Then, in your HTML code:

<img src="myimage.png">
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜