scaleToFit()
Scale the image to fit inside a box, keeping the aspect ratio.
From @jimp/plugin-resize
scaleToFit scales the image to the largest size that fits inside a w × h box without changing its aspect ratio.
One side ends up matching the box and the other is the same size or smaller, so the result is usually not exactly w × h.
Signature
image.scaleToFit(options: { w: number; h: number; mode?: ResizeStrategy; premultiplyAlpha?: boolean;}): thisscaleToFit changes the image in place and returns it, so you can chain more calls after it.
Options
| Option | Type | Default | Description |
|---|---|---|---|
w |
number |
required | The width of the box in pixels. Must be 0 or more. |
h |
number |
required | The height of the box in pixels. Must be 0 or more. |
mode |
ResizeStrategy |
built-in resizer | The resampling algorithm. See resize strategies. |
premultiplyAlpha |
boolean |
true |
Treat alpha as opacity. Pass false when alpha holds other data, to keep the color of transparent pixels. See Alpha that isn’t opacity. |
Example
import { Jimp } from "jimp";
const image = await Jimp.read("photo.jpg");
// 800 x 600 fits a 200 x 200 box as 200 x 150image.scaleToFit({ w: 200, h: 200 });
await image.write("photo-fit.jpg");Try it
Change the box with w and h. The output keeps the dice image’s 4:3 ratio, so only one side matches the box.
image.scaleToFit({ w: 200, h: 200 })Scale up or down to the largest size that fits inside a w x h box, keeping the aspect ratio.
import { Jimp } from "jimp"; const image = await Jimp.read("dice.png"); // Change an option to run it await image.write("output.png");
Notes
-
It enlarges too. Small images are scaled up to fill the box, so a 100 × 75 image in a 1000 × 1000 box becomes 1000 × 750. To only ever shrink, check the size first:
example.ts if (image.width > 200 || image.height > 200) {image.scaleToFit({ w: 200, h: 200 });} -
Both sides are required. Leaving one out fails validation with
Invalid input: expected number, received undefined. To fix only one side, useresizewith justworh. -
Rounding. The factor is applied with
scale, and the new size is rounded to whole pixels. -
Added in 2.0: the
premultiplyAlphaoption, and theLANCZOS,LANCZOS2andMITCHELLstrategies.