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

时间:2022-12-02 21:33:53

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作为库),我需要将Image转换为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:

我试过这个代码只适用于一个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

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

3 个解决方案

#1


2  

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标头的图像受同源策略的约束,无法以这种方式在画布中加载和修改。

#2


2  

I need to convert Image URL to Base64

我需要将Image 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 FileReader to convert img , or other html element to a data URI of html , instead of only img src; i.e.g., try opening console at jsfiddle http://jsfiddle.net/guest271314/9mg5sf7o/ , "right-click" on data URI at console, select "Open link in new tab"

一种可能的解决方法是利用FileReader将img或其他html元素转换为html的数据URI,而不仅仅是img src;例如,尝试在jsfiddle http://jsfiddle.net/guest271314/9mg5sf7o/打开控制台,在控制台的数据URI上“右键单击”,选择“在新标签页中打开链接”

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 iframe element ; utilize XMLHttpRequest to return a Blob , convert Blob to data URI

另一种可行的解决方法是在新选项卡窗口中打开图像;或者是嵌入或iframe元素;利用XMLHttpRequest返回Blob,将Blob转换为数据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();

#3


0  

Do you need something like this?

你需要这样的东西吗?

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

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

#1


2  

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标头的图像受同源策略的约束,无法以这种方式在画布中加载和修改。

#2


2  

I need to convert Image URL to Base64

我需要将Image 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 FileReader to convert img , or other html element to a data URI of html , instead of only img src; i.e.g., try opening console at jsfiddle http://jsfiddle.net/guest271314/9mg5sf7o/ , "right-click" on data URI at console, select "Open link in new tab"

一种可能的解决方法是利用FileReader将img或其他html元素转换为html的数据URI,而不仅仅是img src;例如,尝试在jsfiddle http://jsfiddle.net/guest271314/9mg5sf7o/打开控制台,在控制台的数据URI上“右键单击”,选择“在新标签页中打开链接”

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 iframe element ; utilize XMLHttpRequest to return a Blob , convert Blob to data URI

另一种可行的解决方法是在新选项卡窗口中打开图像;或者是嵌入或iframe元素;利用XMLHttpRequest返回Blob,将Blob转换为数据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();

#3


0  

Do you need something like this?

你需要这样的东西吗?

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

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