Sharp: Resizing image with larger dimension and size

Created on 26 Sep 2016  路  7Comments  路  Source: lovell/sharp

Like to have some suggestions regarding the issue i'm facing currently.

We are allowing image upload and user can choose larger dimension images and large in size.

As of now we are giving some fixed dimension to resize. is there a way to figure out preferred height and width which to be resized based on the image we upload.

ex  var dim1 = getPrefferedSize(4000,5500)  // 1024, 1400
ex  var dim2 = getPrefferedSize(2040,1500)  // 904, 720
question

Most helpful comment

If the output dimensions are to be a percentage of input dimensions then something like the following (untested) should work:

const percentage = 25;
sharp(input).metadata()
  .then(info => {
    const width = Math.round(info.width * percentage / 100);
    const height = Math.round(info.height * percentage / 100);
    return sharp(input).resize(width, height).toBuffer();
  })
  .then(output => {
     ...
  });

All 7 comments

Hello, I'm not quite sure I understand the requirement here. Are the numbers in the comments input dimensions or expected output dimensions? A fully worked example would help me :)

@lovell sorry for not to be clear

When we upload a larger image (4000 x 5000), can we give some percentage instead of width and height, so that it will be resized into lets say 1024 x 1200. Its kind of hard to figure out to which size it should be resized.

I'm looking for a solution so that user will still upload larger images but in node layer we will take care of resizing, considering users can upload different size of images

If the output dimensions are to be a percentage of input dimensions then something like the following (untested) should work:

const percentage = 25;
sharp(input).metadata()
  .then(info => {
    const width = Math.round(info.width * percentage / 100);
    const height = Math.round(info.height * percentage / 100);
    return sharp(input).resize(width, height).toBuffer();
  })
  .then(output => {
     ...
  });

@tomalex0 Does this help answer you question?

Sorry for not updating, this does helped us.
Thanks a lot

If the output dimensions are to be a percentage of input dimensions then something like the following (untested) should work:

const percentage = 25;
sharp(input).metadata()
  .then(info => {
    const width = Math.round(info.width * percentage / 100);
    const height = Math.round(info.height * percentage / 100);
    return sharp(input).resize(width, height).toBuffer();
  })
  .then(output => {
     ...
  });

This would be an awesome example to include in the documentation. I searched for something similar for a long time.

@jrock2468 Commit 703d90e adds a similar example to the docs, thanks for the nudge.

Was this page helpful?
0 / 5 - 0 ratings