【问题标题】:How to convert pre-loaded image into base64 data in jQuery如何在jQuery中将预加载的图像转换为base64数据
【发布时间】: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


    【解决方案1】:

    确保传入实际的 Image 元素(并且已正确加载):

    var a = $('[active_contact][serial=1] img')[0]; // notice [0] at the end = image
    

    【讨论】:

      【解决方案2】:

      您的函数名称不匹配。

      在定义中。它是 getBase64Image,而当你调用它时,你写的是 get_base64_image。

      我一直在寻找这样的代码,而你的代码在更改名称后对我有用。

      【讨论】:

        猜你喜欢
        • 2011-10-15
        • 2014-02-09
        • 1970-01-01
        • 2017-04-24
        • 2021-04-19
        • 1970-01-01
        • 2014-11-03
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多