在 Javascript/Jquery 中将 URL 图像转换为 Base64 或 Blob 的简单方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29606850/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 10:46:41  来源:igfitidea点击:

The easy way to convert an URL Image to Base64 or Blob in Javascript/Jquery

javascriptjqueryimagebase64

提问by Stranger B.

I'm working on an offline mode for a simple application, and I'm using Indexeddb (PounchDB as a library), I need to convert an Image to Base64 or BLOB to be able to save it.

我正在为一个简单的应用程序使用离线模式,并且我正在使用 Indexeddb(PounchDB 作为库),我需要将图像转换为 Base64 或 BLOB 才能保存它。

I have tried this code which works for only one Image (the Image provided) I don't know why it doesn't work for any other image:

我试过这段代码只适用于一个图像(提供的图像)我不知道为什么它不适用于任何其他图像:

function convertImgToBase64URL(url, callback, outputFormat){
    var img = new Image();
    img.crossOrigin = 'Anonymous';
    img.onload = function(){
        var canvas = document.createElement('CANVAS'),
        ctx = canvas.getContext('2d'), dataURL;
        canvas.height = img.height;
        canvas.width = img.width;
        ctx.drawImage(img, 0, 0);
        dataURL = canvas.toDataURL(outputFormat);
        callback(dataURL);
        canvas = null; 
    };
    img.src = url;
}
convertImgToBase64URL('http://upload.wikimedia.org/wikipedia/commons/4/4a/Logo_2013_Google.png', function(base64Img){
alert('it works');
      $('.output').find('img').attr('src', base64Img);  
   
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="output"> <img> </div>

It works fine, but only with one Image, If I try any other Image it doesn't work

它工作正常,但只有一个图像,如果我尝试任何其他图像,它不起作用

回答by adeneo

The image you're using has CORS headers

您使用的图像具有 CORS 标头

Accept-Ranges : bytes
Access-Control-Allow-Origin : * // this one
Age : 69702
Connection : keep-alive

which is why it can be modified in a canvas like that.
Other images that don't have CORS headers are subject to the same-origin policy, and can't be loaded and modified in a canvas in that way.

这就是为什么它可以在这样的画布中进行修改。
其他没有 CORS 标头的图像受同源策略约束,不能以这种方式在画布中加载和修改。

回答by guest271314

I need to convert Image URL to Base64

我需要将图像 URL 转换为 Base64

See

Understanding the HTML5 Canvas image security rules

了解 HTML5 Canvas 图片安全规则

Browser Canvas CORS Support for Cross Domain Loaded Image Manipulation

浏览器画布 CORS 支持跨域加载图像操作

Why does canvas.toDataURL() throw a security exception?

为什么 canvas.toDataURL() 会抛出安全异常?



One possible workaround would be to utilize FileReaderto convert img, or other htmlelement to a data URIof html, instead of only imgsrc; i.e.g., try opening consoleat jsfiddle http://jsfiddle.net/guest271314/9mg5sf7o/, "right-click" on data URIat console, select "Open link in new tab"

一种可能的解决方法是利用FileReaderto convertimg或其他html元素为 a data URIof html,而不仅仅是imgsrc; IEG,请尝试打开console在的jsfiddle http://jsfiddle.net/guest271314/9mg5sf7o/“右键单击”上data URIconsole,选择“在新标签中打开链接”

var elem = $("div")[0].outerHTML;
var blob = new Blob([elem], {
    "type": "text/html"
});
var reader = new FileReader();
reader.onload = function (evt) {
    if (evt.target.readyState === 2) {
        console.log(
                     // full data-uri
                     evt.target.result
                     // base64 portion of data-uri
                   , evt.target.result.slice(22, evt.target.result.length));
        // window.open(evt.target.result)
    };
};
reader.readAsDataURL(blob);


Another possible workaround approach would be to open image in new tab , window; alternatively an embed, or iframeelement ; utilize XMLHttpRequestto return a Blob, convert Blobto data URI

另一种可能的解决方法是在新选项卡中打开图像window;或者一个embed, 或iframe元素; 利用XMLHttpRequest返回一个Blob,转换Blobdata URI

var xhr = new XMLHttpRequest();
// load `document` from `cache`
xhr.open("GET", "", true); 
xhr.responseType = "blob";
xhr.onload = function (e) {
    if (this.status === 200) {
        // `blob` response
        console.log(this.response);
        var reader = new FileReader();
        reader.onload = function(e) {
            // `data-uri`
            console.log(e.target.result);
        };
        reader.readAsDataURL(this.response);        
    };
};
xhr.send();

回答by Hazarapet Tunanyan

Do you need something like this?

你需要这样的东西吗?

http://www.w3docs.com/tools/image-base64

http://www.w3docs.com/tools/image-base64