Isn’t this what the new picture and/or srcset stuff is for? Present the browser with e.g. a uri for a 1x image, a 2x image and a 3x image, and let the browser load the one it needs, based on the device it’s running on?
What inspired me to make this demo was a handful of people asking how to ensure 300ppi embeds in HTML for purposes of rendering a PDF for print - they wanted to ensure that all images, regardless of size, were at a high enough resolution for print at the size they appear in the layout :D
Very interesting. For the curious, this seems to make use of naturalWidth and naturalHeight which are properties of the img element and represent the actual width and height of the image (source: https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement). The 96/300 bit is there, I presume, because the images he chose were saved as 96dpi. I’m guessing you’d want to change this if the dpi was actually different.
But if you know the dpi upfront surely you also know the image size?
I don’t understand the advantage in that case.
Images don’t really have a DPI, they are just a raster of pixels x wide and y tall. This demo is designed as something to show the people wanting to know how to ensure they can print 300dpi images from sources they have embedded in HTML. I had a handful of people ask a very similar question in a timespan of 1 week, so I made a demo to have ready for the next person who asks :D
Most image formats have EXIF or similar metadata - much more than just a raster.
It’s common IIRC to include ‘resolution’ which browsers could (no idea if they do) use when printing.
dpi != ppi: dpi is dots per inch and means printed resolution of ink dots per inch of paper. It has no immediate relevance for the display of an image on a screen, which depends on pixel per inch, or ppi, of the LCD and the software doing the displaying. So, you can save the dpi information in the file for printing, but it will not be used by browsers. The hack presented here “fixes” that by instructing the browser to scale the image down.
All modern browsers use a 96 ppi resolution as the basis for calculating widths: make an element have a width of 1in, it will be displayed as 96 logical CSS pixels. The 96/300 is there to display the image with a density of 300 ppi. So, if I have an image that has a natural width of 300 px, it will always be as wide as an element with width: 1in.
Personally, I think one should instead use the <picture> element to let the browser choose an appropriate image to download. This way no bandwidth is wasted transferring huge images that are scaled down to a third of their width anyway.
Omg, you’re totally right about dpi vs ppi. I knew I was having a brain fart. Thanks for clearing this up.