JavaScript获取图片 image base64 data 方法

Web前端 码拜 9年前 (2015-02-07) 10529次浏览 0个评论

JavaScript获取图片 base64 数据,你需要创建一个canvas元素 with the correct dimensions and copy the image data with the drawImage function. Then you can use the toDataURL function to get a data: url that has the base-64 encoded image. Note that the image must be fully loaded, or you’ll just get back an empty (black, transparent) image.I’ve never written a Greasemonkey script, so you might need to adjust the code to run in that environment.

代码示例如下:


function getBase64Image(img) {
    // 创建一个空的canvas元素
    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,/, "");
}
Getting a JPEG-formatted image doesn't work on older versions (around 3.5) of Firefox, so if you want to support that, you'll need to check the compatibility. If the encoding is not supported, it will default to "image/png".

需要注意的是 image.width 和image.height 返回图片的显示大小在canvas上绘制的时候会剪切图片,所以需要使用naturalWidth 和naturalHeight 替代, 它使用的是真实 图片。

使用中Canvas支持IE9及以上版本,所以低版本中需要使用excanvas.js

Canvas用法参考 使用 HTML5 Canvas 进行数据可视化


CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明JavaScript获取图片 image base64 data 方法
喜欢 (0)
[1034331897@qq.com]
分享 (0)

文章评论已关闭!