Friday, 27 September 2019

resize image using javascript creates blank canvas image

I am resizing the images using javascript and canvas, but some of the resized images are of a black background.

Below is the code:

function resizeImage(input, maxWidth, maxHeight, callback) {
  var data;
    if (input.files && input.files[0]) {
      var reader = new FileReader();
      reader.onload = function (event) {
        var img = new Image();
        img.onload = function () {
          var oc = document.createElement('canvas'), octx = oc.getContext('2d');
          oc.width = img.width;
          oc.height = img.height;
          octx.drawImage(img, 0, 0);
          oc.width = maxWidth;
          oc.height = maxHeight;
          if (img.width > maxWidth) {
            octx.drawImage(oc, 0, 0, oc.width, oc.height);
            octx.drawImage(img, 0, 0, oc.width, oc.height);
            data = oc.toDataURL("image/jpeg", 0.7);
          } else {
            data = oc.toDataURL("image/jpeg", 0.7);
          }
          callback(data);
        };
        img.src = event.target.result;
      };
      reader.readAsDataURL(input.files[0]);
    }
}

function run() {
    resizeImage(
      document.getElementById('image'), 
      600, 600, 
      function(dat) { 
                document.getElementById('preview').src= dat; 
      }
    )
}
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>Resize</title>
</head>
<body>
  <p>Use this image to upload - <a href="https://i.imgur.com/ckNzNNR.jpg">https://i.imgur.com/ckNzNNR.jpg</a> to see the bug.</p>

  <input id="image" type="file" onchange="run()">
  <img id="preview" src="">
  
  <p><b>It creates blank image, works fine for some of the image </b></p>
  
</body>
</html>

Here is the live JS bin, if you want to test the live - https://jsbin.com/kivojewuti/edit?html,js,output

It works for some of the images but not for all images. One of the images where resize image doesn't work is linked in code.

Why does it fail for some of the images?



from resize image using javascript creates blank canvas image

No comments:

Post a Comment