如何在html5,jquery,javascript中获取图像字节字符串(base64)?

我在iPhone或Android中有一个图像,我想通过jQuery AJAX将该文件流或字节串传递给Web Service以在服务器上存储文件。

那么,在HTML5中如何获取图像文件(jpg,gif等)字节字符串,以便我可以将其发布到服务器?

您可以使用canvas.drawImage(image, 0, 0)将图像复制到具有相同大小的canvas,然后使用.toDataURL('image/TYPE')方法来检索图像的base64表示。 然后’TYPE’将是jpg,gif或png

示例:确保当前页面和图像都在同一个域,子域和协议上,否则您将收到安全性错误。 还要确保canvas具有与图像相同的宽度和高度

HTML

   

使用Javascript

 var myImage = document.getElementById('myimage'); var myCanvas = document.getElementById('mycanvas'); var ctx = myCanvas.getContext('2d'); ctx.drawImage(myImage, 0, 0); var mydataURL=myCanvas.toDataURL('image/jpg'); 

要添加到代码示例中以隔离原始数据而不使用字符串开头的格式…

使用Javascript:

 var myImage = document.getElementById('myimage'); var myCanvas = document.getElementById('mycanvas'); var ctx = myCanvas.getContext('2d'); ctx.drawImage(myImage, 0, 0); var myDataURL = myCanvas.toDataURL('image/png');// could also be 'image/jpg' format /* to remove the 'data:image/jpg;base64,' later from using the toDataURL() function (or PNG version data:image/png;base64,') and have only the raw base4 data string, split the result string from the ctx.drawImage() function at the comma and take the second half, and the remaining data will be in tact like so: */ var myBase64Data = myDataURL.split(',')[1];// removes everything up to and including first comma 

我个人喜欢这个,发现使用像indexOf和substring这样的东西更干净,更快