gpt4 book ai didi

javascript - 使用 Phantom.js 将文件加载到图像对象中

转载 作者:行者123 更新时间:2023-11-30 05:31:05 25 4
gpt4 key购买 nike

我正在尝试加载图像并将其数据放入 HTML Image 元素但没有成功。

var fs = require("fs");
var content = fs.read('logo.png');

读取文件内容后,我必须以某种方式将其转换为图像或仅将其打印到 Canvas 上。我试图使用我在 Stack 上找到的代码将二进制数据转换为 Base64 数据 URL。

function base64encode(binary) {
return btoa(unescape(encodeURIComponent(binary)));
}
var base64Data = 'data:image/png;base64,' +base64encode(content);
console.log(base64Data);

返回的 Base64 不是有效的数据 URL。我尝试了更多方法但没有成功。您知道实现该目标的最佳(最短)方法吗?

最佳答案

这是一个相当荒谬的解决方法,但它确实有效。请记住,PhantomJS 的(1.x?) Canvas 有点 broken .所以 canvas.toDataURL 函数返回大量膨胀的编码。具有讽刺意味的是,我发现的最小的是 image/bmp

function decodeImage(imagePath, type, callback) {
var page = require('webpage').create();
var htmlFile = imagePath+"_temp.html";
fs.write(htmlFile, '<html><body><img src="'+imagePath+'"></body></html>');
var possibleCallback = type;
type = callback ? type : "image/bmp";
callback = callback || possibleCallback;
page.open(htmlFile, function(){
page.evaluate(function(imagePath, type){
var img = document.querySelector("img");
// the following is copied from http://stackoverflow.com/a/934925
var canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;

// Copy the image contents to the canvas
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);

// Get the data-URL formatted image
// Firefox supports PNG and JPEG. You could check img.src to
// guess the original format, but be aware the using "image/jpg"
// will re-encode the image.
window.dataURL = canvas.toDataURL(type);
}, imagePath, type);
fs.remove(htmlFile);
var dataUrl = page.evaluate(function(){
return window.dataURL;
});
page.close();
callback(dataUrl, type);
});
}

你可以这样调用它:

decodeImage('logo.png', 'image/png', function(imgB64Data, type){
//console.log(imgB64Data);
console.log(imgB64Data.length);
phantom.exit();
});

或者这个

decodeImage('logo.png', function(imgB64Data, type){
//console.log(imgB64Data);
console.log(imgB64Data.length);
phantom.exit();
});

我尝试了几件事。我无法弄清楚 fs.read 返回的文件编码。我还尝试通过 file://-URL 将文件动态加载到 about:blank DOM 中,但这没有用。因此,我选择将本地 html 文件写入磁盘并立即打开。

关于javascript - 使用 Phantom.js 将文件加载到图像对象中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26978246/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com