如何在html5,jquery,javascript中获取图像字节字符串(base64)? [英] How to get image bytes string (base64) in html5, jquery, javascript?
问题描述
我在iPhone或Android上有一个图像,我想通过jQuery AJAX将该文件流或字节字符串传递给Web服务,以将文件存储在服务器上。
,在HTML5中如何获取图像文件(jpg,gif等)字节字符串,以便将其发布到服务器?
您可以使用 canvas.drawImage(image,0,0)
将图像复制到具有相同尺寸的画布,然后使用。 toDataURL('image / TYPE')
画布的方法检索图像的base64表示。 'TYPE'将是jpg,gif或png
示例:确保当前页面和图像都在同一个域,子域和协议上,否则你会收到安全错误。此外,请确保画布的宽度和高度与图像相同。 HTML
< img src =whatever.jpgid =myimage/>
< canvas width =300height =300id =mycanvasstyle =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');
I have an image in iPhone or Android and I want to pass that file stream or bytes string through jQuery AJAX to Web Service to store file on server.
So, in HTML5 how can I get image file (jpg, gif, etc..) bytes string so I can post that to server?
You could copy the image to a canvas with the same size using canvas.drawImage(image, 0, 0)
and then use the .toDataURL('image/TYPE')
method of the canvas to retrieve the base64 representation of the image. 'TYPE' would then be either jpg, gif or png
Example: Make sure that the current page and the image are both on the same domain, subdomain and protocol otherwise you will get a security error. Also make sure that the canvas has the same width and height as the image
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');
这篇关于如何在html5,jquery,javascript中获取图像字节字符串(base64)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!