将文件输入作为图像插入DOM中

5

两个问题...

基本上,最终我想要一个 file <input>,让用户从他们的文件系统中选择一个图片文件。然后我想在页面上以 img 标签的形式将其显示出来。我之后需要处理它,所以我知道 data: 不是正确的方法,看起来只剩下 blob: 了,但我不知道它是否跨域。

那么,blob: 被认为是跨域的吗?如果我将 <img>@src 设置为 blob: URI,那么我能够对它进行 getImageData() 吗?

如果可以,那么如何实现这一点?我想,如果有人知道如何做,这可能非常简单,但是我的搜索技巧正在失败...

所以:

  • blob: 是否跨域?
  • 如果不是,如何从 file <input> 的内容中派生出 blob: URI?

抱歉,我之前回答的可能没有完全回答你的问题。那么,二进制大对象(blob)真的很重要吗?你想用那张图片做什么?上传?展示? - Marcelo De Zen
我认为文件就是一个二进制大对象。尝试使用 URL.createObjectURL(input.files[0]) - pimvdb
http://html5demos.com/file-api/ 也非常不错。 - haxxerz
2个回答

7
使用URL.createObjectURLFileBlob对象生成一个blob:-URI:

基本演示:http://jsfiddle.net/HGXDT/

​<input type="file" id="file">​​​​​​​​​​​​​​<img id="preview">​​​​​​​​​​​​​​

window.URL = window.URL || window.webkitURL || window.mozURL;
document.getElementById('file')​.onchange = function() {
    var url = URL.createObjectURL(this.files[0]);
    console.log(url);
    document.getElementById('preview').src = url;
};​

检查脚本是否受到同源策略的影响的代码(答案:没有)。 (实际上,页面本身不会受到影响,因为它创建了blob: URI,但其他页面无法在画布上绘制blob: URI并使用它):
http://jsfiddle.net/HGXDT/1/

<input type="file" id="file">
<img id="preview">
<canvas id="canvas"></canvas>
​
window.URL = window.URL || window.webkitURL || window.mozURL;
document.getElementById('file').onchange = function() {
    var url = URL.createObjectURL(this.files[0]);
    console.log(url);
    
    var img = document.getElementById('preview');
    canvasSOPTest(img, url);
};
// See console. SOP error has to show up
canvasSOPTest(new Image(), 'http://stackoverflow.com/favicon.ico?'+new Date());

function canvasSOPTest(img, url) {
    // Same Origin Policy check
    img.onload = function() {
        var canvas = document.getElementById('canvas');
        var ctx = canvas.getContext('2d');
        console.log('Painting image...');
        ctx.drawImage(img, 0, 0);
        console.log('Attempting to get image data');
        try {
            ctx.getImageData(0, 0, canvas.width, canvas.height);
            console.log('Success! No errors');
        } catch (e) {
            console.log(e);
        }
    };
    img.src = url;
}

1
你想要的是使用HTML5文件API来显示图像,然后上传该图像,对吗?
这是一个很好的使用文件API预览图像的例子。

http://html5demos.com/file-api/


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接