4

我正在尝试在手机中制作一个上传图片的网页,但是一旦图片太大,它总是会耗尽内存并且浏览器会退出。这是我的代码:

<input type="file" id="testFile" />
<img src="" style="position:relative;" id="uploadingImg" />

function setImage() {
    var fileList   = this.files;
    var imageType  = /image/;
    for(var i = 0;i < fileList.length;i++) {
        document.getElementById('uploadingImg').file = fileList[i];
        var reader = new FileReader();
        reader.onload = function(e) {
            document.getElementById('uploadingImg').src = e.target.result;
        }
        reader.readAsDataURL(fileList[i]);
    }
}



document.getElementById('testFile').addEventListener('change', setImage, false);

有谁知道如何使用<img>or<canvas>元素预览一张图片?请不要使用"readAsDataURL",因为document.getElementById('uploadingImg').src = e.target.result; 它会耗尽内存。因为base64 Url占用内存太大,内存中存在很多三四份。

如何通过canvas使用"readAsArrayBuffer"和使用?"drawImage"还是其他方法?

如果我可以在本地磁盘中预览一张图片而不使用"readAsDataUrl".

谢谢!

4

1 回答 1

5

In most browsers you don't need to use FileReader (and consequently readAsDataUrl) for this. Instead, you can use the File API's createObjectURL method. Here's your setImage() function rewritten:

function setImage() {
    var file = this.files[0];
    var URL = window.URL || window.webkitURL;
    if (URL.createObjectURL && (file.type == "image/jpeg" || file.type == "image/png" || file.type == "image/gif")) {
        document.getElementById('uploadingImg').src = URL.createObjectURL(file);
    } else {
        alert('Unable to show preview');
    }
}

Browser support is still a bit patchy, though, so check support tables such as caniuse.com before deciding whether to use it: http://caniuse.com/#search=createobjectURL

于 2012-10-30T06:41:59.760 回答