我尝试将本地图像注入 DOM,但没有成功
想象一下,您可以编辑远程站点的 html 内容 - 您怎么可能将图像链接到另一台服务器上且未提供服务的文件?这当然行不通,因为如果您将图像注入到远程页面的 DOM 中,则该图像必须可以通过 http 访问。
所以让我们先试试吧。
page.viewportSize = { width: 188, height: 195 };
page.open(link, function(status) {
page.includeJs('http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js', function() {
// Inject remote image
page.evaluate(function(){
$("body").append("<div style='position: absolute; top:0; left: 0;z-index:9999'><img src='https://images.unsplash.com/photo-1461409971633-aa0e46732112?ixlib=rb-0.3.5&q=80&fm=jpg&crop=entropy&w=640&fit=max&s=bb401d13a08d6459b80bc63a0905a091'></div>");
});
});
// Let's make sure the remote image has time to load
setTimeout(function(){
var clipRect = page.evaluate(function() {
return document.querySelector("body").getBoundingClientRect();
});
page.clipRect = {
top: 0,
left: clipRect.left,
width: 188,
height: 195
};
page.zoomFactor = 0.20;
page.render('thumb.jpg', { format: 'jpg', quality: '100' });
console.log("Thumb Complete");
phantom.exit();
}, 3000);
});
你的脚本生成的原始拇指是这样的(我在cnn.com上操作过):
从 Unsplash 注入远程图像的拇指看起来像这样:
但是必须在外部提供本地映像不太方便 - 如果您的工作机器上没有 http 服务器怎么办,或者如果您在 NAT 后面的本地计算机上工作怎么办?
幸运的是,有一个 PhantomJS 内置服务器形式的简单解决方案:
var server = require('webserver').create();
var fs = require("fs");
var image = fs.open("img.jpg", "rb");
var data = image.read();
var listening = server.listen(3000, function (request, response) {
console.log("GOT HTTP REQUEST");
response.statusCode = 200;
response.headers = {"Cache": "no-cache", "Content-Type": "image/jpeg"};
response.setEncoding("binary");
response.write(data);
response.close();
});
if (!listening) {
console.log("could not create web server listening on port " + port);
phantom.exit();
}
向this answer 致敬,了解如何设置正确的二进制编码。
通过脚本中的这段代码,我们在端口 3000 上启动了一个本地服务器,只是为了提供给定的图像(我想是为了水印目的或类似的目的)。之后我们只需要从本地地址注入一张图片:
page.includeJs('http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js', function() {
page.evaluate(function(){
$("body").append("<div style='position: absolute; top:0; left: 0;z-index:9999'><img src='http://127.0.0.1:3000/'></div>");
});
});
现在这是成功嵌入远程网页缩略图中的本地图像: