我试图拍摄一个网页截图,但图片总是空白(白色)。
我使用这段代码将CALayer转换为Data(从这里取)
extension CALayer {
/// Get `Data` representation of the layer.
///
/// - Parameters:
/// - fileType: The format of file. Defaults to PNG.
/// - properties: A dictionary that contains key-value pairs specifying image properties.
///
/// - Returns: `Data` for image.
func data(using fileType: NSBitmapImageFileType = .PNG, properties: [String : Any] = [:]) -> Data {
let width = Int(bounds.width * self.contentsScale)
let height = Int(bounds.height * self.contentsScale)
let imageRepresentation = NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: width, pixelsHigh: height, bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false, colorSpaceName: NSDeviceRGBColorSpace, bytesPerRow: 0, bitsPerPixel: 0)!
imageRepresentation.size = bounds.size
let context = NSGraphicsContext(bitmapImageRep: imageRepresentation)!
render(in: context.cgContext)
return imageRepresentation.representation(using: fileType, properties: properties)!
}
}然后将数据写入文件为.png。
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!)
{
let d = web.layer?.data() as NSData? //web is the instance of WKWebView
d!.write(toFile: "/Users/mac/Desktop/web.png", atomically: true)
}但是我得到了一个空白的(白色) png,而不是我所期望的
1)。我做错了什么?
2)。有没有其他可能的方法来获得网页的图像表示(使用迅速)?
谢谢!
发布于 2017-06-19 09:51:05
最新更新:
现在,您可以像WKWebView一样使用屏幕截图。
苹果公司增加了新方法代表iOS和macOS,
func takeSnapshot(with snapshotConfiguration: WKSnapshotConfiguration?,
completionHandler: @escaping (NSImage?, Error?) -> Void)但它还在测试阶段。
你不能拍WKWebView的截图。它总是返回一个空白的图像。即使您尝试将WKWebView包含在另一个NSView中并拍摄一个屏幕快照,它也会给您提供空白图像而不是WKWebView。
您应该使用WebView而不是WKWebView来实现您的目的。看看这个问题。
如果您对使用私有框架(苹果不允许您的应用程序进入其商店)感到满意,请查看此GitHub。它是用Obj写的。我不知道Obj,所以我无法解释代码中发生了什么。但它声称做了这项工作。
最好的方法是使用WebView并在WebView上使用您提到的扩展data()。
只是一个问题:为什么不使用phantomJS呢?
PS。抱歉,回复晚了。我没看到你的电子邮件。
https://stackoverflow.com/questions/44597609
复制相似问题