Getting Image Dimensions using Javascript File API

我与影子孤独终老i 提交于 2019-11-26 07:23:50

问题


I require to generate a thumbnail of an image in my Web Application. I make use of the Html 5 File API to generate the thumbnail.

I made use of the examples from the below URL to generate the thumbnails.

http://www.html5rocks.com/en/tutorials/file/dndfiles/

I am successfully able to generate the thumbnails. The problem that I have is I am able to generate thumbnail only by using a static size. Is there a way to get the file dimensions from the selected file and then create the Image object?


回答1:


Yes, read the file as a data URL and pass that data URL to the src of an Image: http://jsfiddle.net/pimvdb/eD2Ez/2/.

var fr = new FileReader;

fr.onload = function() { // file is loaded
    var img = new Image;

    img.onload = function() {
        alert(img.width); // image is loaded; sizes are available
    };

    img.src = fr.result; // is the data URL because called with readAsDataURL
};

fr.readAsDataURL(this.files[0]); // I'm using a <input type="file"> for demonstrating



回答2:


Or use an object URL: http://jsfiddle.net/8C4UB/

var url = URL.createObjectURL(this.files[0]);
var img = new Image;

img.onload = function() {
    alert(img.width);
};

img.src = url;



回答3:


I have wrapped pimvdb answer in a function for general purpose in my project:

function checkImageSize(image, minW, minH, maxW, maxH, cbOK, cbKO){
    //check whether browser fully supports all File API
    if (window.File && window.FileReader && window.FileList && window.Blob) {
        var fr = new FileReader;
        fr.onload = function() { // file is loaded
            var img = new Image;
            img.onload = function() { // image is loaded; sizes are available
                if(img.width < minW || img.height < minH || img.width > maxW || img.height > maxH){  
                    cbKO();
                }else{
                    cbOK();
                }
            };
            img.src = fr.result; // is the data URL because called with readAsDataURL
        };
        fr.readAsDataURL(image.files[0]);
    }else{
        alert("Please upgrade your browser, because your current browser lacks some new features we need!");
    }
}    


来源:https://stackoverflow.com/questions/7460272/getting-image-dimensions-using-javascript-file-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!