2011-03-24 86 views

回答

43

我觉得Get image data in JavaScript?回答你的问题:

// Code taken from MatthewCrumley (https://stackoverflow.com/a/934925/298479) 
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,/, ""); 
} 

传递img标签此功能。它将以base64编码返回图像。它将被重新编码。所以你不能访问原始图像数据。

+3

打败了我,但我也是这么做的。 +1 – Hacknightly 2011-03-24 14:07:54

+2

我把它变成了一个小书签在这里:http://jsfiddle.net/bgmort/m26yr/ 你打开你想要的图像在它自己的标签中,然后运行它,并在屏幕上用数据插入一个textarea网址。 – undefined 2013-03-07 23:21:48

+2

除了“dataURL.replace”,你可以做“dataURL.split(',')[1]”,它也可以用于“png”或“jpg”之外的其他格式。 :) – 2014-02-04 14:11:19

相关问题