From fc1cfb7f60df1abfb7c3bde1ebb7f2286b82d098 Mon Sep 17 00:00:00 2001 From: Jens Tangermann Date: Fri, 17 Jan 2025 18:44:02 +0100 Subject: [PATCH] Fixes #271 optimize js api for cropping --- sample/sample-crop.js | 59 +++++++++++++++++++++++++++++++++++++++++++ src/image.js | 5 ++-- 2 files changed, 62 insertions(+), 2 deletions(-) create mode 100644 sample/sample-crop.js diff --git a/sample/sample-crop.js b/sample/sample-crop.js new file mode 100644 index 0000000..84ca6b8 --- /dev/null +++ b/sample/sample-crop.js @@ -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); + +})(); diff --git a/src/image.js b/src/image.js index 45a8284..3dbfa28 100644 --- a/src/image.js +++ b/src/image.js @@ -415,7 +415,8 @@ class Image { "sharpWebpOptions", "sharpPngOptions", "sharpJpegOptions", - "sharpAvifOptions" + "sharpAvifOptions", + "cacheKey" ].sort(); let hashObject = {}; @@ -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);