简体   繁体   English

使用JavaScript将本地图像转换为base64

[英]Converting a local image to base64 using JavaScript

Iam doing a project in html, javascript only. 我在html中做项目,仅javascript。 I have a function that convert image to base64, see the code below. 我有一个将图像转换为base64的函数,请参见下面的代码。

function getBase64Image()
{
    p = document.getElementById("picField").value;
    img.setAttribute('src', p);
    var canvas = document.createElement("canvas");
    canvas.width = img.width;
    canvas.height = img.height;
    var ctx = canvas.getContext("2d");
    ctx.drawImage(img, 0, 0);
    var dataURL = canvas.toDataURL("image/png");
    var r = dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
    base64 = r;
    alert(base64);
}

but the problem is when I deployed my website, means when I placed my html file on iis, its not working, means in local file system it is showing complete base 64 format like iVb...., but on iis it giving base64 code as just "base,". 但是问题是当我部署网站时,这意味着当我将html文件放置在iis上时,它无法正常工作,这意味着在本地文件系统中,它显示了完整的base 64格式,如iVb ....,但是在iis上却显示了base64代码作为“基础”。 so why it is not working on iis i dont know, so please help me and send me html file that will work on iis too. 所以我不知道为什么它不能在iis上工作,所以请帮助我并向我发送也可以在iis上工作的html文件。

I'm fairly sure you have a Same Origin Policy problem. 我很确定您有一个同源政策问题。

When you run your page on IIS, it runs in a different context than locally: Instead of a file:// URL, it runs on a http:// one. 当您在IIS上运行页面时,它在本地运行的环境与本地环境不同:它不是file:// URL,而是运行在http://站点。

What you are trying to do is fetch a local image file and load it into a canvas on a remote site. 您试图做的是获取本地图像文件,并将其加载到远程站点上的画布中。 That is not possible using traditional JavaScript for security reasons. 出于安全原因,无法使用传统的JavaScript。 (I'm not sure how this works even locally - in my understanding, it shouldn't. But anyway.) (我不确定这在本地是如何工作的-据我所知,它不应该。但是无论如何。)

You will need to use the HTML 5 file API which allows JavaScript direct access to local files. 您将需要使用HTML 5文件API ,该API允许JavaScript直接访问本地文件。 I'll look whether I can dig up some related SO questions. 我将研究是否可以挖掘一些相关的SO问题。

Update: this should help: 更新:这应该有助于:

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

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