0

我正在尝试通过客户端的 html5 filereader api 调整多个图像的大小。它适用于单个图像,但对于多个图像,它通常只上传一个图像并留下其余图像,我不知道是什么问题。这是我的代码

function handleFileSelect(evt) {


        var filesToUpload =  evt.target.files;

         for (var i = 0, f; f = filesToUpload[i]; i++) {



            var img = new Image();
            var reader = new FileReader();
            reader.readAsDataURL(f);
            reader.onload = function(e) {img.src = e.target.result; 
            };


            img.onload = function (){    // also tried reader.onloaded here

            canvas = document.createElement('canvas');
            var ctx = canvas.getContext("2d"); 
            ctx.drawImage(img, 0, 0);



            var MAX_WIDTH = 300;    // 2048
            var MAX_HEIGHT = 150;   // 1600
            var width = img.width;
            var height = img.height;



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


            canvas.width = width;
            canvas.height = height;

            var ctx = canvas.getContext("2d");
            ctx.drawImage(img, 0, 0, width, height);


            var dataurl = canvas.toDataURL("image/jpeg");



            var newImgs = new Image();
            newImgs.src = dataurl;

            document.body.appendChild(newImgs);


        }    

    }
4

0 回答 0