使用canvas和FileReader调整图像大小

时间:2017-04-17 17:07:53

标签: javascript image canvas filereader

我的javascript代码在服务器上正常运行了大约2周。更新Chrome后,它就会停止工作:(

function doUpload() {
    var file = document.getElementById('fileToUpload').files[0];
    EXIF.getData(file, function () {
            var orientation = 0; 
            orientation = EXIF.getTag(this, "Orientation"); 
            var dataUrl = "";
            var img = document.createElement("img");   // Create an image
            var reader = new FileReader();    // Create a file reader

            reader.onload = function(e) {   // Set the image once loaded into file reader
                img.src = e.target.result;

                var canvas = document.createElement("canvas");   

                var MAX_WIDTH = 1080;  // Set Width and Height
                var MAX_HEIGHT = 1080;
                var width = img.width;
                var height = img.height;

                console.log(img.width);

                if (width > height) {
                    if (width > MAX_WIDTH) {
                        height *= MAX_WIDTH / width;
                        width = MAX_WIDTH;
                    }
                ....

问题在于img.widthimg.height都是0。因此,无法调整图像大小。如果我添加console.log(img),我会得到<img src="data:image/jpeg:base 64, 9/j/ 4xg....>,所以我猜图像已正确加载到文件阅读器中,但有些东西会阻止代码工作。我上周没有运气就挣扎着。有没有人看到这个问题?

由于

修改

这是工作代码:

function doUpload() {
    var file = document.getElementById('fileToUpload').files[0];
    EXIF.getData(file, function () {
            var orientation = 0; 
            orientation = EXIF.getTag(this, "Orientation"); 
            var dataUrl = "";
            var img = document.createElement("img");   // Create an image
            var reader = new FileReader();    // Create a file reader

            reader.onload = function(e) {   // Set the image once loaded into file reader

                var canvas = document.createElement("canvas");   

                img.src = e.target.result;

                img.onload = function(){

                var MAX_WIDTH = 1080;  // Set Width and Height
                var MAX_HEIGHT = 1080;
                var width = img.width;
                var height = img.height;

                console.log(img);

0 个答案:

没有答案