如何将图像转换为base64并避免同源策略 [英] How to be able to convert image to base64 and avoid same-origin Policy

查看:176
本文介绍了如何将图像转换为base64并避免同源策略的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将图像(链接)转换为base64以便能够存储在浏览器端(IndexedDB),但我无法做到这一点,我一直在寻找解决方案,我和我没有解决我的问题。

I'm trying to convert an image (link) to base64 to be able to store in the Browser side (IndexedDB), but i'm not able to do that, I have been looking for a solution for days and I didn't a solution to my problem.

在这个很棒的代码中,我能够将图像从互联网转换为Base64,但问题是我不能因为同源策略而对互联网上的其他图像执行此操作。

In this awesome code I'm able to convert an image from internet to Base64, but the problem is that I can't do that for other images on internet because of the Same-origin policy.

我如何能够避免该问题或者您知道转换图像的任何其他解决方案到Base64,这将非常有帮助

How I would be able to avoid that problem or if you know any other solution to convert an image to Base64, that would be really helpful

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>

推荐答案

您需要先将图像下载到字节数组:
使用XMLHttpRequest下载二进制数据,不使用overrideMimeType

You need to download the image to a byte array first: Downloading binary data using XMLHttpRequest, without overrideMimeType

var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://www.celticfc.net/images/doc/celticcrest.png', true);

xhr.responseType = 'arraybuffer';

xhr.onload = function(e) {
   if (this.status == 200) {
       var uInt8Array = new Uint8Array(this.response); // Note:not xhr.responseText

       for (var i = 0, len = uInt8Array.length; i < len; ++i) {
           uInt8Array[i] = this.response[i];
       }

       var byte3 = uInt8Array[4]; // byte at offset 4
   }
}

xhr.send();

然后你可以按如下方式使用字节数组: Javascript:如何使用Javascript或Servlet显示来自字节数组的图像?

Then you can use the byte array as follows: Javascript : How to display image from byte array using Javascript or Servlet?

<img id="ItemPreview" src="" />

document.getElementById("ItemPreview").src = "data:image/png;base64," + YourByteArray;

编辑:我不能尝试这台ATM,但您也可以使用HTML5将文件保存到文件系统FileSystem API:如何保存带有图片网址的图片到HTML5文件系统

I cannot try this ATM but you can alternatively save the file to the file system using the HTML5 FileSystem API: How to save a image to HTML5 filesystem with the url of image

window.requestFileSystem(window.PERSISTENT, 2*1024*1024, onFileSystemSuccess, fail);


function onFileSystemSuccess(fileSystem) {
    fs = fileSystem;
    console.log('File system initialized');

    saveAsset('http://www.example-site-with-cors.com/test.png');
}


function saveAsset(url, callback, failCallback) {
    var filename = url.substring(url.lastIndexOf('/')+1);

    // Set callback when not defined
    if (!callback) {
        callback = function(cached_url) {
            console.log('download ok: ' + cached_url);
        };
    }
    if (!failCallback) {
        failCallback = function() {
            console.log('download failed');
        };
    }

    // Set lookupTable if not defined
    if (!window.lookupTable)
        window.lookupTable = {};

    // BlobBuilder shim
    // var BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder || window.MSBlobBuilder;

    var xhr = new XMLHttpRequest();
    xhr.open('GET', url, true);
    // xhr.responseType = 'blob';
    xhr.responseType = 'arraybuffer';

    xhr.addEventListener('load', function() {

        fs.root.getFile(filename, {create: true, exclusive: false}, function(fileEntry) {
            fileEntry.createWriter(function(writer) {

                writer.onwrite = function(e) {
                    // Save this file in the path to URL lookup table.
                    lookupTable[filename] = fileEntry.toURL();
                    callback(fileEntry.toURL());
                };

                writer.onerror = failCallback;

                // var bb = new BlobBuilder();
                var blob = new Blob([xhr.response], {type: ''});
                // bb.append(xhr.response);
                writer.write(blob);
                // writer.write(bb.getBlob());

            }, failCallback);
        }, failCallback);
    });

    xhr.addEventListener('error', failCallback);
    xhr.send();

    return filename;
}



function fail(evt) {
    console.log(evt.target.error.code);
}

这篇关于如何将图像转换为base64并避免同源策略的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆