Skip to content

Instantly share code, notes, and snippets.

@jorilallo
Created December 19, 2018 22:15
Show Gist options
  • Save jorilallo/23282a4887ab8ef166182c1dab1677f0 to your computer and use it in GitHub Desktop.
Save jorilallo/23282a4887ab8ef166182c1dab1677f0 to your computer and use it in GitHub Desktop.
Detect DPI information for a PNG image to determine if it's retina quality or not. This can be done by reading optional physical pixel dimensions chunk which both macOS and Windows attach to the image data.
import extract from "png-chunks-extract";
/**
* Detect if PNG image is in retina resolution.
*
* PNG Chunk documentation: https://www.w3.org/TR/PNG-Chunks.html
*/
const determineRetinaUpload = async (imageUrl) => {
let retinaImage = false;
const response = await fetch(imageUrl);
if (response.ok && response.headers.get("content-type") === "image/png") {
// Read image content into buffer and extract PNG chunks
const buffer = await response.arrayBuffer();
const chunks = extract(new Uint8Array(buffer));
// Decode physical pixel dimensions chunk
let pHYs;
const pHYsChunk = chunks.find(chunk => chunk.name === "pHYs");
if (pHYsChunk) {
const metersToInchMultiplies = 39.3701;
const buffer = Buffer.from(pHYsChunk.data);
const xDpu = buffer.readUIntBE(0, 4);
const yDpu = buffer.readUIntBE(4, 4);
const xDpi = Math.round(xDpu / metersToInchMultiplies);
const yDpi = Math.round(yDpu / metersToInchMultiplies);
const unit = buffer.readUIntBE(8, 1) === 1 ? "meter" : undefined;
pHYs = {
xDpu,
yDpu,
xDpi,
yDpi,
unit
};
}
if (pHYs) {
retinaImage =
pHYs.unit === "meter" && pHYs.xDpi >= 144 && pHYs.yDpi >= 144;
}
}
return retinaImage;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment