简体   繁体   English

如何将图像转换为base64

[英]how convert the image to base64

im using this below function to encode the image using html5 canvas that im getting from user (here im using local imagefile) 即时通讯使用以下功能来编码使用html5画布对图像进行编码,即时通讯是从用户那里获取的(此处即时通讯使用本地imagefile)

jsfunction js功能

function imgToDataURL(img) {
var canvas = document.createElement('canvas');
canvas.width = img.naturalWidth;
canvas.height = img.naturalHeight;
var c = canvas.getContext('2d');
c.drawImage(img, 0, 0);
var dataURL = canvas.toDataURL("image/png");
return dataURL;
}

its giving localimage cannot be loaded how to overcome this problem & is there any other way to encode the image to base64 它的给定localimage无法加载如何克服此问题,还有其他方法可以将图像编码为base64

To produce data-uris with canvas you need to make sure cross-origin resource sharing (CORS) requirements are fulfilled. 要使用canvas生成数据uri,您需要确保满足跨域资源共享 (CORS)的要求。

Loading an image from local file:// is considered a different origin than the page (or the effect thereof). 从本地file://加载图像被认为与页面来源不同(或其效果)。 If your image simply doesn't load you need to make sure the path to the image is correct as well. 如果图像根本无法加载,则需要确保图像路径也正确。

In any case, to be able to load an image that you can later extract from a canvas element as data-uri, you need to make sure that the image is loaded from the same origin using a local installed server such as for example light-weight Mongoose or similar (LAMP/WAMP etc.). 在任何情况下,为了能够加载稍后可以从canvas元素中提取的图像作为data-uri,您需要确保使用本地安装的服务器(例如,light-重量猫鼬或类似(LAMP / WAMP等)。

For a public server the same applies but in some cases an external server may allow that images are used cross-origin. 对于公共服务器,这同样适用,但是在某些情况下,外部服务器可能允许跨源使用映像。 In those cases you can request such usage by setting the crossOrigin property on the image to "anonymous" before setting the src . 在这些情况下,可以通过在设置src之前将图像上的crossOrigin属性设置为"anonymous"请求这种用法。 This won't work with local images though. 但是,这不适用于本地图像。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM