js 把图片转化为base64编码

js 把图片转化为base64编码

function getBase64Image(img) {
    // 创建一个空的canvas元素 img为html img对象
    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,/, "");
}

  

posted @ 2021-07-04 19:36  he大力出奇迹  阅读(723)  评论(0)    收藏  举报