Files
web/packages/design-system/lib/components/Image/imageLoader.ts
Joakim Jäderberg 8c3f8c74db Merged in feature/SW-3365-blurry-images (pull request #2746)
Feature/SW-3365 reduce upscaling of images (fix blurry images)

* fix: handle when images are wider than 3:2 but rendered in a 3:2 container

* use dimensions everywhere applicable

* fall back to using <img sizes='auto' /> if possible

* imageLoader: never nest

* remove empty test file


Approved-by: Anton Gunnarsson
Approved-by: Matilda Landström
2025-09-02 17:52:31 +00:00

58 lines
1.5 KiB
TypeScript

import { ImageLoaderProps } from 'next/image'
export const imageLoader =
({
dimensions,
}: {
focalPoint?: { x: number; y: number }
dimensions?: { width: number; height: number }
}) =>
({ quality, src, width }: ImageLoaderProps) => {
const isAbsoluteUrl =
src.startsWith('https://') || src.startsWith('http://')
const hasQS = src.indexOf('?') !== -1
if (
dimensions &&
isLargerThanAspectRatio(dimensions, '3:2') &&
width < dimensions.width
) {
// If image is wider than 3:2, compensate for low height when rendering in a 3:2 container
const scale = width / dimensions.width
const minWidthFor32Aspect =
dimensions.height * scale * aspectRatios['3:2'] * 2
width = Math.max(minWidthFor32Aspect, width)
}
if (width < 500) {
// Compensate for bad resizing library used by netlify
width += width / 2
}
width = roundToNearest(width, 10)
if (isAbsoluteUrl) {
return `https://img.scandichotels.com/.netlify/images?url=${src}&w=${width}${quality ? '&q=' + quality : ''}`
}
return `${src}${hasQS ? '&' : '?'}w=${width}${quality ? '&q=' + quality : ''}`
}
const aspectRatios = {
'3:2': 3 / 2,
}
function isLargerThanAspectRatio(
dimensions: {
width: number
height: number
},
aspectRatio: keyof typeof aspectRatios
) {
return dimensions.width / dimensions.height > aspectRatios[aspectRatio]
}
function roundToNearest(value: number, nearest: number) {
return Math.ceil(value / nearest) * nearest
}