Sharp: withoutEnlargement not working if combined with crop

Created on 18 Apr 2018  路  4Comments  路  Source: lovell/sharp

given the following code:

sharp(inputFile).resize(width, height).crop().withoutEnlargement().jpeg({quality: 100}).toFile(outputFile)

the image is enlarged to match width and height also if the original dimensions are less than the specified ones in resize.
I would expect that withoutEnlargement doesn't allow the enlargement

question

All 4 comments

http://sharp.pixelplumbing.com/en/stable/api-resize/#withoutenlargement

Do not enlarge the output image if the input image width or height are already less than the required dimensions. This is equivalent to GraphicsMagick's > geometry option: "change the dimensions of the image only if its width or height exceeds the geometry specification".

Use with max() to preserve the image's aspect ratio.

Please note this says "width or height" rather than "width and height".

There are no example dimensions provided here but my best guess would be that the scenario described requires max instead of crop.

Thank you for the reply @lovell but the thing I'm trying to do is to actually crop the image, let's say to 16:9 starting from an image 1:1
Using max I will obtain a 1:1 image.

If the starting image is 500x500 and I call:
sharp(inputFile).resize(1000, 1000/16*9).crop().withoutEnlargement().jpeg({quality: 100}).toFile(outputFile)

I would like to obtain a 500x(500/16*9) image, so having the max width and height <= than the original image.

For now I resolved it programmatically, I check the original image width and height and I change the params for resize accordingly:

// inputFile, width and aspectRatio are coming as params

var image = sharp(inputFile);

image
        .metadata()
        .then(function (metadata) {

          width = Math.min(width, metadata.width);
          var height = round(width / aspectRatio);
            if (height > metadata.height) {
              height = metadata.height;
              width = round(height * aspectRatio);
            }

          return image
              .resize(width, height)
              .crop()
  })

Thanks for providing example dimensions as these always makes these things easier to work through.

If you want to scale by a factor (aspectRatio in this case) rather than resize one or both dimensions of an image to absolute values then will have to use your suggested approach that performs a calculation based on the input dimensions.

See also #236 for a related future possible enhancement.

I see. Thank you so much @lovell for the quick replies and thank you for your work with this project

Was this page helpful?
0 / 5 - 0 ratings

Related issues

terbooter picture terbooter  路  3Comments

OleVik picture OleVik  路  3Comments

sansroman picture sansroman  路  3Comments

kachurovskiy picture kachurovskiy  路  3Comments

emmtte picture emmtte  路  3Comments