将图像加载到FileReader中 [英] Load image into FileReader

查看:118
本文介绍了将图像加载到FileReader中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将网址中的图片加载到文件阅读器中,以获取该图片的数据网址。我试图在谷歌上搜索解决方案,但我只能找到从本地计算机上的文件输入中读取它们的解决方案。

I want to load an image from an url into filereader in order to obtain a data url of that image. I tried to search for the solution on google but i can only find solutions to read them from the file input on a local computer.

推荐答案

如果你想要一个可用的图像数据URI表示,那么我建议在< img> 标签中加载图像,在<$ c上绘制它$ c>< canvas> 然后使用画布的 .toDataURL()方法。

If you want a usable data-URI representation of the image, then I suggest to load the image in a <img> tag, paint it on a <canvas> then use the .toDataURL() method of the canvas.

否则,您需要使用 XMLHttpRequest 来获取图像blob(在XMLHttpRequest上设置 responseType 属性实例并从 .response 属性中获取blob。然后,您可以照常使用 FileReader API。

Otherwise, you need to use XMLHttpRequest to get the image blob (set the responseType property on the XMLHttpRequest instance and get the blob from the .response property). Then, you can use the FileReader API as usual.

在这两种情况下,图像都必须托管在必须启用相同的来源或CORS。

In both cases, the images have to be hosted on the same origin, or CORS must be enabled.

如果您的服务器不支持CORS,您可以使用添加CORS标头的代理。在以下示例中(使用第二种方法),我正在使用 CORS Anywhere 在我想要的任何图像上获取CORS头。

If your server does not support CORS, you can use a proxy that adds CORS headers. In the following example (using the second method), I'm using CORS Anywhere to get CORS headers on any image I want.

var x = new XMLHttpRequest();
x.open('GET', '//cors-anywhere.herokuapp.com/http://www.youtube.com/favicon.ico');
x.responseType = 'blob';
x.onload = function() {
    var blob = x.response;
    var fr = new FileReader();
    fr.onloadend = function() {
        var dataUrl = fr.result;
        // Paint image, as a proof of concept
        var img = document.createElement('img');
        img.src = dataUrl;
        document.body.appendChild(img);
    };
    fr.readAsDataURL(blob);
};
x.send();

以前的代码可以复制粘贴到控制台,你会看到一个带有YouTube的小图片页面底部的图标。链接到演示: http://jsfiddle.net/4Y7VP/

The previous code can be copy-pasted to the console, and you will see a small image with YouTube's favicon at the bottom of the page. Link to demo: http://jsfiddle.net/4Y7VP/

这篇关于将图像加载到FileReader中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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