Skip to content

Commit

Permalink
Fixes 11ty#271
Browse files Browse the repository at this point in the history
optimize js api for cropping
  • Loading branch information
jens-struct committed Jan 17, 2025
1 parent d262378 commit fc1cfb7
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 2 deletions.
59 changes: 59 additions & 0 deletions sample/sample-crop.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
const eleventyImage = require("../");
const Sharp = require("sharp");

const src = "../test/bio-2017.jpg";
const cropRatio = 16 / 7;

async function sanitizeWidths(widths) {
const {
width: originalWidth,
height: originalHeight,
} = await Sharp(src).metadata();

const sanitizedWidths = widths.filter(width => {
const height = Math.floor(width / cropRatio);
return width <= originalWidth && height <= originalHeight;
});

if (sanitizedWidths.length < widths.length) {
sanitizedWidths.push(getMaxCropWidth(originalWidth, originalHeight));
}

return sanitizedWidths;
}

function getMaxCropWidth(originalWidth, originalHeight) {
const cropWidth = originalWidth;
const cropHeight = Math.floor(originalWidth / cropRatio);

if (cropHeight > originalHeight) {
return getMaxCropWidth(originalWidth - 1, originalHeight);
}

return cropWidth;
}

(async () => {

const widths = await sanitizeWidths([100, 300, 500, 1600, 3200]);

console.log(widths);

const results = await eleventyImage(src, {
widths,
formats: ["webp"],
dryRun: true,
transform: function(sharp, stats) {
sharp.resize({
width: stats.width,
height: Math.floor(stats.width / cropRatio),
fit: Sharp.fit.cover,
position: Sharp.strategy.entropy,
});
},
cacheKey: cropRatio,
});

console.log(results);

})();
5 changes: 3 additions & 2 deletions src/image.js
Original file line number Diff line number Diff line change
Expand Up @@ -415,7 +415,8 @@ class Image {
"sharpWebpOptions",
"sharpPngOptions",
"sharpJpegOptions",
"sharpAvifOptions"
"sharpAvifOptions",
"cacheKey"
].sort();

let hashObject = {};
Expand Down Expand Up @@ -681,7 +682,7 @@ class Image {
throw new Error("Expected `function` type in `transform` option. Received: " + transform);
}

await transform(sharpInstance);
await transform(sharpInstance, { ...stat });

// Resized in a transform (maybe for a crop)
let dims = Image.getDimensionsFromSharp(sharpInstance, stat);
Expand Down

0 comments on commit fc1cfb7

Please sign in to comment.