开发者

load local image into UIWebView

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


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==)';


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];


You haven't saved the image to that path.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜