Next.js Discord

Discord Forum

Adjusting srcSet based on DPR

Unanswered
Orinoco Crocodile posted this in #help-forum
Open in Discord
Orinoco CrocodileOP
Hey, I'm using the Image component to display a 128x128px image:

<Image
    src={icon}
    alt="Icon"
    width="128"
    height="128"
/>

By default, this get transformed into img with this srcset:
<img ... srcset="
    /_next/image?url=icon.png&w=128&q=75 1x,
    /_next/image?url=icon.png&w=256&q=75 2x"
/>


As I am on 1440p screen with 1.25DPR, this cause an issue as I get the 1x image and it doesn't look sharp. I'd like to adjust the srcSet to add an 1.25x variant:
<img ... srcset="
    /_next/image?url=icon.png&w=128&q=75 1x,
    /_next/image?url=icon.png&w=160&q=75 1.25x,
    /_next/image?url=icon.png&w=256&q=75 2x"
/>


But I can not figure out how to do that, I tried playing with the sizes prop, but that causes the srcset to explode using configured image/device sizes rather than to just use DPR. (1/1.25/2) 🤔

Technically, I can modify the image config to force only the specific sizes I want:
deviceSizes: [],
imageSizes: [128, 160, 256],
// ...
<Image
    src={icon}
    alt="Icon"
    sizes="128px"
/>

But that that feels overly elaborate especially since I am not adjusting size of the image on the page, only its density.

1 Reply

Orinoco CrocodileOP
Looking through the source code, it looks like there is no way around this so I ended up patching Next:
https://github.com/martinkadlec0/next.js/commit/97cae5bfc5d94e6777ad87210d47ff8b41ace8a9

I haven't actually tried to build this, I just used pnpm patch next and copy pasted my changes to dist/ in the patch folder. It works, but you also need to add the additional sizes to imageSizes if you want Next to use correct size for each density:
images: {
    densities: [1, 1.25, 1.5, 2],
    imageSizes: [16, 32, 48, 64, 96, 128, 160, 192, 256, 384],
}