How to generate a thumbnail image after adding an image inside an input type=“file” in a form and submitting them both on the same form

后端 未结 5 988
误落风尘
误落风尘 2020-11-30 19:58

I have a form which allows the user to upload a picture. After the user has submitted the form, I\'d like to generate on the front-end a thumbnail for each picture and then

5条回答
  •  我在风中等你
    2020-11-30 20:26

    Building on top of what Allesandro wrote to something more pragmatic.

    The function takes a file from the File API and tries to fit it in the boundBox while preserving the aspect ratio. Nothing is drawn, but instead you get back a Promise that spits the dataUrl generated.

    // Creates a thumbnail fitted insize the boundBox (w x h)
    generateThumbnail(file, boundBox){
      if (!boundBox || boundBox.length != 2){
        throw "You need to give the boundBox"
      }
      var scaleRatio = Math.min(...boundBox) / Math.max(file.width, file.height)
      var reader = new FileReader();
      var canvas = document.createElement("canvas")
      var ctx = canvas.getContext('2d');
    
      return new Promise((resolve, reject) => {
        reader.onload = function(event){
            var img = new Image();
            img.onload = function(){
                var scaleRatio = Math.min(...boundBox) / Math.max(img.width, img.height)
                let w = img.width*scaleRatio
                let h = img.height*scaleRatio
                canvas.width = w;
                canvas.height = h;
                ctx.drawImage(img, 0, 0, w, h);
                return resolve(canvas.toDataURL(file.type))
            }
            img.src = event.target.result;
        }
        reader.readAsDataURL(file);
      })
    }
    

    It can be used like below

    generateThumbnail(file, [300, 300]).then(function(dataUrl){
        console.log(dataUrl)
    })
    

提交回复
热议问题