feat: Add aspect ratio support to imgproxy loader and apply 16:9 aspect ratio to featured images across blog posts and recent posts.
This commit is contained in:
@@ -23,17 +23,37 @@ export default function imgproxyLoader({
|
||||
return src;
|
||||
}
|
||||
|
||||
// Check if src contains custom gravity query parameter
|
||||
// Check if src contains custom gravity or aspect ratio query parameters
|
||||
let gravity = 'sm'; // Use smart gravity (content-aware) by default
|
||||
let cleanSrc = src;
|
||||
let calculatedHeight = 0;
|
||||
let resizingType: 'fit' | 'fill' = 'fit';
|
||||
|
||||
try {
|
||||
// Dummy base needed for relative URLs
|
||||
const url = new URL(src, 'http://localhost');
|
||||
const customGravity = url.searchParams.get('gravity');
|
||||
const aspectRatio = url.searchParams.get('ar'); // e.g. "16:9"
|
||||
|
||||
if (customGravity) {
|
||||
gravity = customGravity;
|
||||
url.searchParams.delete('gravity');
|
||||
}
|
||||
|
||||
if (aspectRatio) {
|
||||
const parts = aspectRatio.split(':');
|
||||
if (parts.length === 2) {
|
||||
const arW = parseFloat(parts[0]);
|
||||
const arH = parseFloat(parts[1]);
|
||||
if (!isNaN(arW) && !isNaN(arH) && arW > 0) {
|
||||
calculatedHeight = Math.round(width * (arH / arW));
|
||||
resizingType = 'fill'; // Must use fill to allow imgproxy to crop
|
||||
}
|
||||
}
|
||||
url.searchParams.delete('ar');
|
||||
}
|
||||
|
||||
if (customGravity || aspectRatio) {
|
||||
cleanSrc = src.startsWith('http') ? url.href : url.pathname + url.search;
|
||||
}
|
||||
} catch (e) {
|
||||
@@ -41,10 +61,11 @@ export default function imgproxyLoader({
|
||||
}
|
||||
|
||||
// We use the width provided by Next.js for responsive images
|
||||
// Height is set to 0 to maintain aspect ratio
|
||||
// Height is calculated from aspect ratio if provided, otherwise 0 to maintain aspect ratio
|
||||
return getImgproxyUrl(cleanSrc, {
|
||||
width,
|
||||
resizing_type: 'fit',
|
||||
height: calculatedHeight,
|
||||
resizing_type: resizingType,
|
||||
gravity,
|
||||
});
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user