Image resize before upload

后端 未结 9 1542
闹比i
闹比i 2020-11-28 03:09

I need to provide a means for a user to upload photos to their web site in jpeg format. However, the photos are very large in original size, and I would like to make the re

9条回答
  •  無奈伤痛
    2020-11-28 03:27

    In 2011, we can know do it with the File API, and canvas. This works for now only in firefox and chrome. Here is an example :

    var file = YOUR_FILE,
        fileType = file.type,
        reader = new FileReader();
    
    reader.onloadend = function() {
      var image = new Image();
          image.src = reader.result;
    
      image.onload = function() {
        var maxWidth = 960,
            maxHeight = 960,
            imageWidth = image.width,
            imageHeight = image.height;
    
        if (imageWidth > imageHeight) {
          if (imageWidth > maxWidth) {
            imageHeight *= maxWidth / imageWidth;
            imageWidth = maxWidth;
          }
        }
        else {
          if (imageHeight > maxHeight) {
            imageWidth *= maxHeight / imageHeight;
            imageHeight = maxHeight;
          }
        }
    
        var canvas = document.createElement('canvas');
        canvas.width = imageWidth;
        canvas.height = imageHeight;
    
        var ctx = canvas.getContext("2d");
        ctx.drawImage(this, 0, 0, imageWidth, imageHeight);
    
        // The resized file ready for upload
        var finalFile = canvas.toDataURL(fileType);
      }
    }
    
    reader.readAsDataURL(file);
    

提交回复
热议问题