2012-10-18 43 views
8

我在iPhone或Android中有一个图像,我想通过jQuery AJAX将该文件流或字节字符串传递给Web服务以将文件存储在服务器上。如何在html5,jquery,javascript中获取图像字节字符串(base64)?

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

+0

保存使用jQuery的图像源'道具('和'使用$阿贾克斯()' – Johan

+0

发送确定图像保存在一些文件夹&我可以读取,但我怎么能将它们转换为字节字符串 –

回答

9

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

示例:确保当前页面和图像都位于相同的域,子域和协议上,否则会出现安全错误。还要确保画布具有相同的宽度和高度作为图像

HTML

<img src="whatever.jpg" id="myimage" /> 
<canvas width="300" height="300" id="mycanvas" style="display: none;"></canvas> 

的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'); 
+0

你有工作网址或例子? –

+0

查看最新编辑 – devnull69

+0

非常感谢:) –

3

要添加到代码示例而不在格式以分离所述原始数据字符串的开头...

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和子

+0

这是一个如何解决错误“输入不是有效的Base-64字符串,因为它包含一个非基本的64个字符”的例子,当处理数据时,数据URL部分仍然在前面。原始数据仍然是压缩的JPG或PNG格式。 –

相关问题