package com.ankurm.imagegen; import java.util.Optional; /** * Decides what a byte array is from its first bytes, ignoring every label the sender supplied * (file name, MIME type, URL suffix). Only four raster formats are recognised; SVG, HTML, PDF and * anything else come back empty and are refused by the caller. * *

Sniffing the magic number is necessary, not sufficient: a file can start like a PNG and * carry anything after it. That is why {@link ImageVerifier} also decodes it and why the store * pins the Content-Type itself. See the article's "safe storage" section. */ public final class ImageSniffer { private ImageSniffer() {} public static Optional sniff(byte[] b) { if (b == null || b.length < 12) { return Optional.empty(); } if (u(b, 0) == 0x89 && b[1] == 'P' && b[2] == 'N' && b[3] == 'G' && u(b, 4) == 0x0D && u(b, 5) == 0x0A && u(b, 6) == 0x1A && u(b, 7) == 0x0A) { // IHDR: length(4) "IHDR"(4) width(4) height(4) int w = b.length >= 24 ? be32(b, 16) : 0; int h = b.length >= 24 ? be32(b, 20) : 0; return Optional.of(new Sniffed("image/png", "png", w, h)); } if (u(b, 0) == 0xFF && u(b, 1) == 0xD8 && u(b, 2) == 0xFF) { int[] wh = jpegSize(b); return Optional.of(new Sniffed("image/jpeg", "jpg", wh[0], wh[1])); } if (b[0] == 'G' && b[1] == 'I' && b[2] == 'F' && b[3] == '8' && (b[4] == '7' || b[4] == '9') && b[5] == 'a') { int w = u(b, 6) | (u(b, 7) << 8); int h = u(b, 8) | (u(b, 9) << 8); return Optional.of(new Sniffed("image/gif", "gif", w, h)); } if (b[0] == 'R' && b[1] == 'I' && b[2] == 'F' && b[3] == 'F' && b[8] == 'W' && b[9] == 'E' && b[10] == 'B' && b[11] == 'P') { return Optional.of(new Sniffed("image/webp", "webp", 0, 0)); } return Optional.empty(); } /** Walks JPEG segments to the first start-of-frame marker. Returns {0, 0} if none is found. */ private static int[] jpegSize(byte[] b) { int i = 2; while (i + 9 < b.length) { if (u(b, i) != 0xFF) { i++; continue; } int marker = u(b, i + 1); if (marker == 0xFF) { i++; continue; } if (marker == 0xD8 || marker == 0x01 || (marker >= 0xD0 && marker <= 0xD7)) { i += 2; continue; } int len = (u(b, i + 2) << 8) | u(b, i + 3); boolean sof = marker >= 0xC0 && marker <= 0xCF && marker != 0xC4 && marker != 0xC8 && marker != 0xCC; if (sof) { int h = (u(b, i + 5) << 8) | u(b, i + 6); int w = (u(b, i + 7) << 8) | u(b, i + 8); return new int[] {w, h}; } i += 2 + len; } return new int[] {0, 0}; } private static int u(byte[] b, int i) { return b[i] & 0xFF; } private static int be32(byte[] b, int i) { return (u(b, i) << 24) | (u(b, i + 1) << 16) | (u(b, i + 2) << 8) | u(b, i + 3); } }