Search code examples
node.jsimageimage-resizingaspect-ratio

Resize image keeping aspect ratio and fit in bounds nodejs


I need to resize images to fit in a specific dimensions. I want to keep aspect ratio.

For example

original image:
w:634
h:975

resize to max:
w:50
h:100

result:
w:50
h:85

I have not found anything that could do that(calculations for w and h) and I am too dumb to figure it out by myself

copilot suggested me something that just keeps aspect ratio

If you want to use packages. I prefer jimp for image editing.


Solution

  • Calculate the aspect ratio of your original image and of your maximum dimensions. According to that ratios, either take the maximum width or height as fixed and calculate the other side accordingly.

    let 
      oheight = 634, owidth = 975,
      mheight = 50, mwidth = 100,
      theight, twidth;
    
    
    let 
       oratio = owidth/oheight, // (~1.54)
       mratio = mwidth/mheight, // (2)
       
    
    if (mratio > oratio) {
      //original image is "higher" so take the maximum height
      //and calculate the width accordingly
      theight = mheight;  //50
      twidth = theight * oratio; //77
    } else {
      //original image is "wider" so take the maximum width
      //and calculate the height accordingly
      twidth = mwidth;
      theight = twidth / oratio;
    }
    

    But any decent image processing library will have the functionality, that you can pass in the maximum dimensions and define to keep the aspect ratio and will do these calculations internally ...