Skip to content

Commit

Permalink
Merge pull request #190 from JaredReisinger/largest-non-upscale
Browse files Browse the repository at this point in the history
Ensure original size is included if any widths are larger and `!allowUpscale`
  • Loading branch information
zachleat committed Feb 2, 2024
2 parents 3f0fd25 + e44acb4 commit e17ff95
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 10 deletions.
20 changes: 10 additions & 10 deletions img.js
Original file line number Diff line number Diff line change
Expand Up @@ -191,20 +191,20 @@ class Image {
// Convert strings to numbers, "400" (floats are not allowed in sharp)
valid = valid.map(width => parseInt(width, 10));

// Replace any larger-than-original widths with the original width if upscaling is not allowed.
// This ensures that if a larger width has been requested, we're at least providing the closest
// non-upscaled image that we can.
if (!allowUpscale) {
valid = valid.map(width => width > originalWidth ? originalWidth : width);
}

// Remove duplicates (e.g., if null happens to coincide with an explicit width
// or a user passes in multiple duplicate values)
// or a user passes in multiple duplicate values, or multiple larger-than-original
// widths have resulted in the original width being included multiple times)
valid = [...new Set(valid)];

// filter out large widths if upscaling is disabled
let filtered = valid.filter(width => allowUpscale || width <= originalWidth);

// if the only valid width was larger than the original (and no upscaling), then use the original width
if(valid.length > 0 && filtered.length === 0) {
filtered.push(originalWidth);
}

// sort ascending
return filtered.sort((a, b) => a - b);
return valid.sort((a, b) => a - b);
}

static getFormatsArray(formats, autoFormat, svgShortCircuit) {
Expand Down
15 changes: 15 additions & 0 deletions test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -1097,3 +1097,18 @@ test("SVG files svgShortCircuit based on file size (brotli compression)", async
t.is(stats.webp[1].format, "svg");
t.is(stats.webp[1].width, 900);
});

test("#184: Ensure original size is included if any widths are larger", async t => {
// Test image is 1280px wide; before PR for 184, asking for [1500, 900] would
// result in only the 900px image. Now, it should result in 900px *and* 1280px
// images.
let stats = await eleventyImage("./test/bio-2017.jpg", {
widths: [1500, 900],
formats: ['jpeg'],
dryRun: true,
});

t.is(stats.jpeg.length, 2);
t.is(stats.jpeg[0].width, 900);
t.is(stats.jpeg[1].width, 1280);
});

0 comments on commit e17ff95

Please sign in to comment.