I am trying to resize images/transform to png with Nodejs sharp package without cropping. According to documentation it is .max() method, which regretfully does not work (image is croped) when resizing to png. Any workarounds?
2 Answers
If your using sharp, then you can achieve your desired result using
sharp()
.resize(400, 400, {
fit: sharp.fit.inside,
withoutEnlargement: true, // if image's original width or height is less than specified width and height, sharp will do nothing(i.e no enlargement)
})
inside: will fit image inside width 400 and height 400 without cropping any portion of your image and without adding black padding for dimenstion adustment to the output image- Technically it resizes the image to be as large as possible while ensuring its dimensions are less than or equal to both those specified.
Comments
Hey if you're still wondering, this is how you can do it.
await sharp(postImage).resize(800, 900, {fit:"contain"}).toFile("/output/path");
In the third parameter of .resize() you can need to mention the fit, it can be 'fill', 'contain', etc. 'contain' will embed the image not changing its original height & width & padding with background color (def. black). 'fill' will stretch out the image. For More