0

I have a file input that only accepts images. When the image loads, I add it to an Image variable. I'm trying to make the image have a max width. Here's my code:

const reader = new FileReader();
reader.readAsDataURL(e.target.files[0]);

reader.onload = function (loadEvt) {
    var newImage = new Image();
    newImage.src = loadEvt.target.result;

    // do something with newImage
};

I tried doing: new Image(200, 'auto'); but it didn't keep the aspect ratio. How can I give a max width while still keeping the images original aspect ratio?

Jessica
  • 9,379
  • 14
  • 65
  • 136
  • 1
    One option is to use `width` and `height` attribute in `` tag that will make it look different dimensions, but if you want to truly change image dimensions it can be done with canvas https://stackoverflow.com/q/19262141/6160662 – Vinay Jun 11 '20 at 03:38
  • Just a tip: `newImage = URL.createObjectURL(e.target.files[0])` – Endless Jun 11 '20 at 10:02

1 Answers1

0

you can do this

const reader = new FileReader();
reader.readAsDataURL(e.target.files[0]);

reader.onload = function (loadEvt) {
    var newImage = new Image(200);
    //if you only set width,height may auto.else height is so
    newImage.src = loadEvt.target.result;

    // do something with newImage
};

you can run code on https://codepen.io/wzc570738205/pen/gOPPNvo?editors=1010

Joinwang
  • 110
  • 6