我指的是Get image data in JavaScript?
使用 jQuery,我想将预加载的 img 转换为 Base64 编码数据。我按照以下方式尝试了在提到的网址中找到的函数,但出现了错误。
我从提到的链接中找到的函数:
function getBase64Image(img) {
// Create an empty canvas element
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.
var dataURL = canvas.toDataURL("image/png");
return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
}
我如何尝试:
var a = $('[active_contact][serial=1] img');
console.log(get_base64_image(a));
我从 firbug 控制台收到的错误:
TypeError: Argument 1 of CanvasRenderingContext2D.drawImage could not be converted to any of: HTMLImageElement, HTMLCanvasElement, HTMLVideoElement.
get_base64_image()
ctx.drawImage(img, 0, 0);
我怎样才能让这个东西发挥作用?我想使用 jQuery 将预加载的图像转换为 base64 以供重复使用。有更好的想法欢迎提出。
最佳答案
确保您传入实际的 Image 元素(并且它已正确加载):
var a = $('[active_contact][serial=1] img')[0]; // notice [0] at the end = image
关于javascript - 如何在 jQuery 中将预加载的图像转换为 Base64 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27099677/