Skip to content

Commit f868f33

Browse files
committed
keep a side at one pixel in scale
1 parent ff774d1 commit f868f33

2 files changed

Lines changed: 12 additions & 1 deletion

File tree

‎src/image.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -980,7 +980,9 @@ export class Image {
980980
*/
981981
protected __scale__(factor: number, mode: ResizeMode = 'bilinear', fast = true): Image {
982982
if (factor === 1) return this;
983-
return this.__resize__(this.width * factor, this.height * factor, mode, fast);
983+
// (a side doesn't shrink below one pixel, like resize({ width }) keeping the aspect ratio)
984+
const size = (side: number): number => factor > 0 ? Math.max(1, side * factor) : side * factor;
985+
return this.__resize__(size(this.width), size(this.height), mode, fast);
984986
}
985987

986988
/**

‎tests/option-checks.js‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,15 @@ const rejects = async (name, fn, Type, pattern) => {
8383
await rejects('resize mode', () => image.clone().resize(4, 4, {mode: 'lanczos'}), TypeError, /resize mode must be 'nearest-neighbor', 'bilinear', 'bicubic' or 'area', not 'lanczos'/);
8484
await rejects('scale mode', () => image.clone().scale(2, {mode: 'lanczos'}), TypeError, /resize mode must be/);
8585
await rejects('blend mode', () => image.clone().composite(image, {mode: 'nope'}), TypeError, /blend mode must be/);
86+
87+
// scale() doesn't shrink a side below one pixel, like resize({ width }) keeping the aspect ratio
88+
{
89+
const thin = new Image(7, 1).scale(0.5);
90+
if (thin.width !== 3 || thin.height !== 1) panic(`new Image(7, 1).scale(0.5) is ${thin.width}x${thin.height}`);
91+
const tiny = new Image(10, 3).scale(0.01);
92+
if (tiny.width !== 1 || tiny.height !== 1) panic(`scale(0.01) is ${tiny.width}x${tiny.height}`);
93+
for (const factor of [0, -1, NaN]) await rejects(`scale(${factor})`, () => image.clone().scale(factor), RangeError, /./);
94+
}
8695
await rejects('flip direction', () => image.clone().flip('diagonal'), TypeError, /flip direction must be 'horizontal' or 'vertical'/);
8796
await rejects('disposal mode', () => new Frame(image, {disposalMode: 'none'}), TypeError, /disposal mode must be/);
8897
await rejects('wrapStyle', () => Image.renderText('hi', {font: new Uint8Array(4), size: 8, wrapStyle: 'line'}), TypeError, /wrapStyle must be 'word' or 'char'/);

0 commit comments

Comments
 (0)