load local image into UIWebView

2019-04-16 14:11发布

I want to take a screenshot and then send to webview a local path for it, so it will show it. I know that webview could take images from NSBundle but this screenshots are created dynamically - can I add something to it by code?

I was trying it like this:

  UIGraphicsBeginImageContext( webView.bounds.size);    
    [self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();    

    NSString *file = @"myfile.png";
    NSString *directory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES) objectAtIndex:0];
    NSString *path = [directory stringByAppendingPathComponent: file];
    [UIImagePNGRepresentation(viewImage) writeToFile:path atomically:YES];

    NSString *function = [NSString stringWithFormat:@"loadImagePlease(%@);",path];
    [ ad stringByEvaluatingJavaScriptFromString:function];

But loadImageFunction can't access it , with file:/// or file:// prefix. What's the solution? Thanks for ANY help.

EDIT: added a missing line in code

SOLUTION: I used a Cyrille's advice and this library for encoding : http://cocoawithlove.com/2009/06/base64-encoding-options-on-mac-and.html

3条回答
ゆ 、 Hurt°
2楼-- · 2019-04-16 14:28

You haven't saved the image to that path.

查看更多
beautiful°
3楼-- · 2019-04-16 14:29

If you don't need to store the image, you can convert it to NSData and load the UIWebView directly, skipping the URL altogether:

NSData *data = UIImagePNGRepresentation(viewImage);
[myUIView loadData:data MIMEType:@"image/jpeg" textEncodingName:@"UTF-8" baseURL:nil];

UPDATED:

Since you do need to store the file, use NSFileManager to get the URL of your directory, then use the URL to write to and retrieve the file:

NSURL *pathUrl = [[NSFileManager defaultManager] URLForDirectory:directory inDomains:NSDocumentDirectory appropriateForURL:nil create:NO error:nil];
NSURL *fileUrl = [pathUrl URLByAppendingPathComponent:file];
[UIImagePNGRepresentation(viewImage) writeToURL:fileUrl atomically:YES];
NSString *urlString = [fileUrl absoluteString];
查看更多
我只想做你的唯一
4楼-- · 2019-04-16 14:47

Convert it to a base64 data URI scheme and send that via Javascript as you're currently doing :

someDOMelement.src = 'url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO 9TXL0Y4OHwAAAABJRU5ErkJggg==)';

查看更多
登录 后发表回答