【发布时间】:2014-11-24 07:19:32
【问题描述】:
我指的是Get image data in JavaScript?
使用 jQuery,我想将预加载的 img 转换为 base64 编码数据。我以以下方式尝试了在提到的 url 中找到的功能,但结果出现了错误。
我从提到的链接中找到的功能:
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 以重复使用。欢迎任何更好的想法。
【问题讨论】:
标签: javascript jquery base64