gpt4 book ai didi

javascript - Base64 编码图像警报正确,响应为零

转载 作者:行者123 更新时间:2023-11-28 18:07:15 24 4
gpt4 key购买 nike

我正在尝试对 URL 中的图像进行 Base64 编码。

function getBase64Image(url) {
var img = new Image(),
response = '';

img.setAttribute('crossOrigin', 'anonymous');
img.onload = function() {
var canvas = document.createElement('canvas');
canvas.width = this.width;
canvas.height = this.height;

var ctx = canvas.getContext('2d');
ctx.drawImage(this, 0, 0);

var dataURL = canvas.toDataURL('image/png');
response = dataURL;
alert(response);
};

img.src = url;
return response;
}

alert() 工作正常,但响应为零:

alert

如果我像这样记录响应(在屏幕截图中完成了两次),您可以在屏幕截图的控制台中看到它不会返回任何内容:

console.log(getBase64Image('<%= asset_path "test.jpg" %>'));

显然我们可以读取图像,因为警报具有编码。我错过了什么?

更新

相关 JSFiddle: https://jsfiddle.net/guxzxq20/3/

最佳答案

方法: Canvas

将图像加载到图像对象中,将其绘制到未受污染的 Canvas 上,并将 Canvas 转换回 dataURL。

function convertImgToDataURLviaCanvas(url, callback, outputFormat) {
var img = new Image();
img.crossOrigin = 'Anonymous';
img.onload = function() {
var canvas = document.createElement('CANVAS');
var ctx = canvas.getContext('2d');
var dataURL;
canvas.height = this.height;
canvas.width = this.width;
ctx.drawImage(this, 0, 0);
dataURL = canvas.toDataURL(outputFormat);
callback(dataURL);
canvas = null;
};
img.src = url;
}

调用方法

convertImgToDataURLviaCanvas('http://upload.wikimedia.org/wikipedia/commons/4/4a/Logo_2013_Google.png',function(response){
alert(response)
});

关于javascript - Base64 编码图像警报正确,响应为零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42349827/

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