Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ensure original size is included if any widths are larger and !allowUpscale #190

Merged
merged 3 commits into from
Feb 2, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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);
});