DEV Community

Depth-Map.com
Depth-Map.com

Posted on

How to Tell If a PNG Is Really 16-bit: Read the Header, Then Count the Gray Levels

I keep running into the same bug in depth maps and height maps: the file says it is 16-bit, and the pixels say otherwise. Image viewers will not tell you. A viewer shows you gray, and 256 grays and 65,536 grays look the same on a monitor.

The difference only appears downstream, when something turns brightness into height. A CNC toolpath, a laser engraver or a displacement modifier samples that gray as a distance. If the file really holds 256 distinct values, the surface has 256 terraces however many bits the header claims.

So there are two separate facts to check, and neither one is enough on its own.

Fact 1: the bit depth in the header

A PNG starts with an 8-byte signature, followed by chunks. The first chunk is always IHDR, and it holds the width, the height, the bit depth, the colour type and the interlace flag. For a depth map you want colour type 0 (grayscale) and bit depth 16.

That field describes the container, not the content. A 16-bit PNG can hold any 8-bit image: write each 8-bit value v as v * 257 (so 255 becomes 65,535) and the header is honest about the container while the content is still 8-bit. Plenty of exporters, resizers and "convert to 16-bit" buttons do exactly that.

Fact 2: how many distinct levels are actually there

Count the unique pixel values. A genuinely 16-bit field with a smooth surface has thousands of them. A stretched 8-bit field has at most 256, and every one is a multiple of 257. That second detail is a useful fingerprint, because a real 16-bit file would not land only on multiples of 257 by chance.

Two caveats before you trust the count:

  • A small image caps the count. A 64×64 image has at most 4,096 distinct pixels, so a low count there proves nothing. Use the full-size export.
  • A flat scene has few levels for an honest reason. A depth map of a flat plate with one small boss on it genuinely contains few values. A low count is a warning, not a verdict. Use it together with the header, and look for the multiples-of-257 pattern.

A browser-or-Node snippet

Do not try to count levels by drawing the PNG onto a <canvas> and calling getImageData: by default the canvas hands back 8-bit RGBA, so a 16-bit file is flattened before you ever see it. You have to read the PNG bytes yourself.

This version reads the header, then inflates the pixel data and undoes the PNG row filters, for plain non-interlaced grayscale files in 8 or 16 bit. It uses DecompressionStream, which exists in Node 18+ and in current browsers (I ran it only in Node 24 for this article; in a browser, pass it new Uint8Array(await file.arrayBuffer())).

// inspect_png.mjs  -  node inspect_png.mjs file.png
import { readFileSync } from "node:fs";

async function inspectPng(buf) {
  const dv = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
  let pos = 8, hdr = null;
  const idat = [];
  while (pos < buf.length) {
    const len = dv.getUint32(pos);
    const type = String.fromCharCode(...buf.subarray(pos + 4, pos + 8));
    const data = buf.subarray(pos + 8, pos + 8 + len);
    if (type === "IHDR") {
      hdr = { width: dv.getUint32(pos + 8), height: dv.getUint32(pos + 12),
              bitDepth: data[8], colorType: data[9], interlace: data[12] };
    } else if (type === "IDAT") idat.push(data);
    pos += 12 + len;
  }
  if (hdr.colorType !== 0 || hdr.interlace || ![8, 16].includes(hdr.bitDepth)) return hdr;

  const raw = new Uint8Array(await new Response(
    new Blob(idat).stream().pipeThrough(new DecompressionStream("deflate"))).arrayBuffer());
  const bpp = hdr.bitDepth / 8, stride = hdr.width * bpp;
  let prev = new Uint8Array(stride), cur = new Uint8Array(stride);
  const seen = new Set();
  for (let y = 0; y < hdr.height; y++) {
    const f = raw[y * (stride + 1)];
    const line = raw.subarray(y * (stride + 1) + 1, (y + 1) * (stride + 1));
    for (let i = 0; i < stride; i++) {
      const a = i >= bpp ? cur[i - bpp] : 0, b = prev[i], c = i >= bpp ? prev[i - bpp] : 0;
      let p = 0;
      if (f === 1) p = a; else if (f === 2) p = b; else if (f === 3) p = (a + b) >> 1;
      else if (f === 4) {
        const pa = Math.abs(b - c), pb = Math.abs(a - c), pc = Math.abs(a + b - 2 * c);
        p = pa <= pb && pa <= pc ? a : pb <= pc ? b : c;
      }
      cur[i] = (line[i] + p) & 255;
    }
    for (let x = 0; x < hdr.width; x++)
      seen.add(bpp === 2 ? (cur[2 * x] << 8) | cur[2 * x + 1] : cur[x]);
    [prev, cur] = [cur, prev];
  }
  return { ...hdr, uniqueLevels: seen.size };
}

for (const path of process.argv.slice(2))
  console.log(path, await inspectPng(new Uint8Array(readFileSync(path))));
Enter fullscreen mode Exit fullscreen mode

It deliberately returns only the header for RGB, palette, interlaced or low-bit-depth files rather than guessing.

The same check in Python

If you already have numpy and Pillow, it is much shorter. The header is read straight from the file, so you see what the file itself declares rather than what Pillow decided to hand you.

import sys
import numpy as np
from PIL import Image

for path in sys.argv[1:]:
    with open(path, "rb") as fh:
        head = fh.read(26)
    bit_depth, color_type = head[24], head[25]       # IHDR fields
    px = np.array(Image.open(path))
    levels = np.unique(px)
    print(f"{path}: header {bit_depth}-bit, colour type {color_type}, "
          f"{levels.size} unique levels, min {px.min()}, max {px.max()}")
    if bit_depth == 16:
        print("  all values multiples of 257:", bool(np.all(levels % 257 == 0)))
Enter fullscreen mode Exit fullscreen mode

I generated three synthetic test scenes (a dome, a ramp and a coin-like medallion), saved each as a true 16-bit PNG, as an 8-bit image stretched into a 16-bit container, and as a plain 8-bit PNG. This is what the Python script printed for the dome, with the same counts from the JavaScript version:

dome-true-16bit.png: header 16-bit, colour type 0, 12240 unique levels, min 0, max 65535
  all values multiples of 257: False
dome-stretched-8bit-in-16bit.png: header 16-bit, colour type 0, 253 unique levels, min 0, max 65535
  all values multiples of 257: True
dome-plain-8bit.png: header 8-bit, colour type 0, 253 unique levels, min 0, max 255
Enter fullscreen mode Exit fullscreen mode

The first two files have identical headers and look nearly identical on screen. Only the count separates them: 12,240 against 253. (The stretched file has 253 rather than 256 because the dome never visits three of the 256 possible levels. That is normal.)

The one-liner, if you have ImageMagick

With ImageMagick 7 installed, identify can print both facts for a grayscale file:

identify -format "%z-bit | %k unique levels\n" file.png
Enter fullscreen mode Exit fullscreen mode

On the same dome files it printed 16-bit | 12240 unique levels, 16-bit | 253 unique levels and 8-bit | 253 unique levels, matching the Python counts. I ran this on ImageMagick 7.1.2 in a Q16 build. Two things to watch: a Q8 build reads at 8 bits, and %k counts unique colours, so it only means "gray levels" for a grayscale file.

Skip the code if you only need an answer

If you only have one file to check and do not want to run anything, the 16-bit depth map checker does the same two things in the browser: it compares the header bit depth with the measured unique level count and flags a 16-bit file with 256 or fewer levels. The page says it decodes the PNG locally and does not upload it. I work on Depth-Map.com, the site that hosts it, so weigh that accordingly. The scripts above are the better choice for batch checks and CI.

Why it matters for 3D printing and CNC

Height is range divided by levels. A 3 mm relief written with 256 levels has steps of about 3 mm / 256 ≈ 11.7 µm. The same range with 65,536 levels is about 46 nm per step, far finer than any printer or cutter can resolve. You rarely need all of that precision, but you do want enough levels that the steps disappear below the machine's own resolution, and a stretched 8-bit file never gets there.

Also note that v * 257 is only one way a file ends up like this. A file saved through an 8-bit step anywhere in the pipeline (a screenshot, a JPEG, an editor in 8-bit mode) loses the extra levels for good, and re-saving it as 16-bit does not bring them back.

A short checklist for a pipeline:

  1. Check the IHDR bit depth is 16 and the colour type is 0.
  2. Count unique levels on the full-size file and compare with what the scene should contain.
  3. Check whether every value is a multiple of 257.
  4. Never round-trip the file through an 8-bit editor or a canvas.

Fail any of these and the fix is upstream, in whatever produced the file.

Top comments (0)