2011-05-26 56 views
5

是否可以将HTML页面转换为可可中的图像?将HTML文档转换为可可中的图像

其实我已经在HTML中创建了完整的视图,现在我想要将整个html预览转换为图像(任何jpeg或png等)。

我在网上找不到任何资源或样本,这对我的上述查询提供了某种帮助。非常感谢,如果有人能分享他的智慧,我可以如何实现这一点。

在此先感谢..

+0

你喜欢在iOS中做这个吗? – 2011-05-26 09:25:40

回答

7

首先,我要感谢塞尔吉奥......他的回答让我开始了,但我想我会分享一些我没有发现明显的代码,以使其工作:

下面是如何使一个页面的缩略图时无需它显示:最后

- (void)webViewDidFinishLoad:(UIWebView *)webView { 
    UIGraphicsBeginImageContext(webView.bounds.size); 
    [webView.layer renderInContext:UIGraphicsGetCurrentContext()]; 
    UIImage *webViewImage = UIGraphicsGetImageFromCurrentImageContext(); 
    UIGraphicsEndImageContext(); 
    NSData *thumbnailData = UIImagePNGRepresentation(webViewImage); 
    [webView removeFromSuperview]; 
} 

,显示该缩略图you'l:

// Your width and height can be whatever you like, but if you want this to render 
// off screen, you need an x and y bigger than the superview's width and height 
UIWebView* webView = [[UIWebView alloc] initWithFrame:CGRectMake(largerScreenDimension, largerScreenDimension, largerScreenDimension, largerScreenDimension)]; 
[self.view addSubview:webView]; // UIWebViews without an assigned superview don't load ever. 
webView.delegate = self; // or whoever you have implement UIWebViewDelegate 
webView.scalesToFit = YES; // This zooms the page appropriately to fill the entire thumbnail. 
[webView loadRequest:[NSURLRequest requestWithURL:url]]; 

然后在你的委托实现这个我需要这样的东西:

thumbnailImageView.image = [UIImage imageWithData:thumbnailData]; 

作为一件额外的事情,我会提到,我想要一次生成多个缩略图。我发现使用objc_setAssociatedObject()objc_getAssociatedObject()对跟踪哪个webView加载哪个缩略图非常有帮助。不过,详细讨论这个问题的效果如何超出了这个问题的范围。

+0

很好的答案。只有一件小事我无法工作。我不希望图像以任何比例。所以我试图关闭scaleToFit并将自己的宽度和高度放在initWithFrame中。但是,现在我得到一个空的图像。有任何想法吗?谢谢 – hishamaus 2015-02-12 06:21:36

+0

@hishamaus:如果你还有其他问题,你应该单独发布,我想。我最近没有使用Obj-C,所以我不知道如何回答你的问题。 – ArtOfWarfare 2015-02-13 20:53:38

3

可以绘制在图像方面您认为是这样的:

UIWebView* view = ... 
.... 
UIGraphicsBeginImageContext(view.bounds.size);  
[view.layer renderInContext:UIGraphicsGetCurrentContext()]; 
UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext(); 
UIGraphicsEndImageContext(); 
NSData *imagedata = UIImagePNGRepresentation(viewimage); 
NSString *encodedString = [imageData base64Encoding]; 

另一种选择是使用Quartz PDF引擎创建一个PDF。

+0

其实我试图在QuickLook插件中使用图片作为缩略图,所以使用webview是不可能的。在此先感谢.. – 2011-05-26 09:40:57

+0

@Vinaj Jain:我在那里放了一个'UIWebView',因为你说过“我已经在HTML中创建了完整的视图,现在我想转换整个HTML预览”。所以这就是你所拥有的,我想。我的代码会创建一个'UIImage',你可以将它放在你的插件中,它可以用你在屏幕上绘制的任何视图。 – sergio 2011-05-26 09:44:06

+0

okkk ...我会尽力...非常感谢您的帮助... – 2011-05-26 09:53:51