我一直在尝试在Javascript中将图片转换为base64字符串。到目前为止,我在stackoverflow上找到了这个代码,我能够将jpeg和png图像转换为各自的base64字符串。但是,当我尝试将GIF转换为base64时,它会进行转换,但字符串始终具有:
data:image/png;base64,............................<string continues>
当我尝试打开它时,gif图像无法正常工作。
应该是:
data:image/gif;base64,............................<string continues>
以下是代码:
function convertImgToBase64(url,callback,outputFormat){
var canvas = document.createElement('CANVAS'),
ctx = canvas.getContext('2d'),
img = new Image;
img.crossOrigin = 'Anonymous';
img.onload = function(){
var dataURL;
canvas.height = img.height;
canvas.width = img.width;
ctx.drawImage(img,0,0);
dataURL = canvas.toDataURL(outputFormat || 'image/png');
callback.call(this, dataURL);
canvas = null;
};
img.src = url;
}
我从网址传递图片,例如:http://www.howtogeek.com/wp-content/uploads/2010/10/DANCING_BABY.gif
请帮忙。