Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to resize an image in sharp with the option 'contain' but preserve the aspect ratio of the original dimensions?

I have a 1000px by 750px image.

I use lovell/sharp to resize it:

await sharp(image)
    .resize({
        fit: sharp.fit.contain,
        width: 800,
        height: 800
    })
    .jpeg({ quality: 80 })
    .toBuffer()

This results in a new image that is 800px by 800px, with the original image 'contained' inside of that region.

What I would really like is to have a final image that is 800px by 600px. IOW, to resize the image and preserve the aspect ratio.

I realize it is possible to do this by specifying only a width. However it is useful to have a bounding box to contain the resized image in, to avoid creating images greater than a certain height.

Can I do this in sharp with different settings?

like image 669
user1031947 Avatar asked Oct 22 '19 16:10

user1031947


People also ask

How do I resize an image without changing the aspect ratio?

Press-and-hold the Shift key, grab a corner point, and drag inward to resize the selection area. Because you're holding the Shift key as you scale, the aspect ratio (the same ratio as your original photo) remains exactly the same.

How do I resize an image in sharp?

The resizeImage() function chains the sharp module's resize() method to the sharp instance. The method takes an object as an argument. In the object, you set the image dimensions you want using the width and height property. Setting the width to 150 and the height to 97 will make the image 150px wide, and 97px tall.

How do I resize an image using CSS without losing the aspect ratio?

The Simple Solution Using CSS By setting the width property to 100%, you are telling the image to take up all the horizontal space that is available. With the height property set to auto, your image's height changes proportionally with the width to ensure the aspect ratio is maintained.


3 Answers

Keep either width or height so that the Sharp will maintain the ratio

Below the height will maintain its ratio when resizing;

await sharp(image)
    .resize({
        fit: sharp.fit.contain,
        width: 800
    })
    .jpeg({ quality: 80 })
    .toBuffer()
like image 96
mapmalith Avatar answered Oct 22 '22 14:10

mapmalith


What I think you are willing to achieve:

await sharp(image)
    .resize(800, 800, {
        fit: 'inside',
    })
    .jpeg({ quality: 80 })
    .toBuffer()
like image 37
Cesar Morillas Avatar answered Oct 22 '22 12:10

Cesar Morillas


Pass a string to the fit property.

    let resizedPhoto
    await sharp(photoBuffer)
      .resize({ width: 1200, height: 900, fit: 'fill' })
      .toBuffer()
      .then((data) => {
        resizedPhoto = data
      })
      .catch((err) => {})
like image 1
Premo89 Avatar answered Oct 22 '22 14:10

Premo89