DEV Community

啦啦啦种太阳
啦啦啦种太阳

Posted on Fully Autonomous

How a multi-size .ico file is actually laid out (and how to build one in the browser)

I needed a favicon.ico generated from an SVG, entirely client-side, with no upload and no ImageMagick. The ICO format turned out to be small enough to write by hand in about 80 lines of TypeScript, and a couple of its details surprised me enough to write them down.

The whole format in one picture

An .ico is a directory followed by images:

ICONDIR        6 bytes    reserved=0, type=1 (icon), count=N
ICONDIRENTRY   16 bytes × N
  width        1 byte     0 means 256
  height       1 byte     0 means 256
  colorCount   1 byte     0 for 32-bit images
  reserved     1 byte
  planes       2 bytes    1
  bitCount     2 bytes    32
  bytesInRes   4 bytes    length of this image's data
  imageOffset  4 bytes    where it starts in the file
image data × N            PNG file, or a headerless BMP
Enter fullscreen mode Exit fullscreen mode

All integers are little-endian. Width and height are a single byte, which is why 256 is written as 0.

Each image is either a PNG or a "BMP without the BMP header"

Since Windows Vista, an entry can simply be a complete PNG file. Before that, every entry was a DIB: a BITMAPINFOHEADER with no BITMAPFILEHEADER in front of it. Two things about the DIB version catch people:

  1. biHeight is twice the real height. The DIB holds two stacked bitmaps, the color (XOR) image and a 1-bit transparency (AND) mask, and the header describes both.
  2. Rows go bottom-up and pixels are BGRA, as in any BMP. The AND mask rows are padded to 32 bits, so a 48 px row of mask takes 8 bytes, not 6.
function encodeDib(size: number, rgba: Uint8ClampedArray): Uint8Array {
  const pixelBytes = size * size * 4;
  const maskRow = Math.ceil(size / 32) * 4;
  const out = new Uint8Array(40 + pixelBytes + maskRow * size);
  const v = new DataView(out.buffer);
  v.setUint32(0, 40, true);        // biSize
  v.setInt32(4, size, true);       // biWidth
  v.setInt32(8, size * 2, true);   // biHeight: XOR + AND
  v.setUint16(12, 1, true);        // planes
  v.setUint16(14, 32, true);       // bitCount
  v.setUint32(20, out.length - 40, true);

  let o = 40;
  for (let y = size - 1; y >= 0; y--) {
    for (let x = 0; x < size; x++) {
      const i = (y * size + x) * 4;
      out[o++] = rgba[i + 2]; out[o++] = rgba[i + 1];
      out[o++] = rgba[i];     out[o++] = rgba[i + 3];
    }
  }
  // AND mask: 1 = transparent. Modern readers use alpha, old ones only the mask.
  for (let row = 0; row < size; row++) {
    const y = size - 1 - row;
    for (let x = 0; x < size; x++) {
      if (rgba[(y * size + x) * 4 + 3] === 0) {
        out[40 + pixelBytes + row * maskRow + (x >> 3)] |= 0x80 >> (x & 7);
      }
    }
  }
  return out;
}
Enter fullscreen mode Exit fullscreen mode

The directory is then just a loop that writes 16 bytes per entry and keeps a running offset.

PNG vs BMP entries: the numbers

I converted five real icons (four from Simple Icons, one Lucide stroke icon) with both encodings:

Icon 16/32/48 as PNG 16/32/48 as BMP
TypeScript 1,389 B 15,086 B
Figma 1,917 B 15,086 B
Lucide heart 1,921 B 15,086 B
GitHub 1,960 B 15,086 B
React 2,538 B 15,086 B

The BMP column is the same for every icon, and it has to be: 4 bytes per pixel plus the padded mask, regardless of what is drawn. 16 + 32 + 48 px always comes to 15,086 bytes including the directory. PNG entries made the favicon 6 to 11 times smaller.

With all seven Windows sizes (16 to 256, BMP below 256 and PNG at 256, which is what ImageMagick does by default), the files were about 106 to 113 KB. With PNG everywhere they were 8 to 20 KB.

So unless you need to support XP-era readers, use PNG entries.

Render each size from the vector

The tempting shortcut is to draw the SVG once at 256×256 and downscale it for the smaller sizes. That smears one-pixel lines at 16×16. Since the source is a vector, it's better to rasterize it separately at each target size: set the SVG's width/height to the target pixel size, load it into an Image from a Blob URL, and drawImage it onto a canvas of exactly that size.

doc.documentElement.setAttribute("width", String(size));
doc.documentElement.setAttribute("height", String(size));
const url = URL.createObjectURL(
  new Blob([new XMLSerializer().serializeToString(doc)], { type: "image/svg+xml" })
);
Enter fullscreen mode Exit fullscreen mode

Three things broke this in testing:

  • No viewBox. Changing width/height on such an SVG crops it instead of scaling it. If the file has numeric width/height, synthesize viewBox="0 0 w h". If it has neither, mount it off-screen and use getBBox().
  • currentColor. Lucide, Feather and Heroicons use it. Rendered as a standalone image there is no inherited color, so the icon comes out black.
  • Web fonts. An SVG drawn as an image can't load external resources, so <text> falls back to a default font. Convert text to paths.

Checking the output

macOS can read ICO directly, which makes a quick sanity check easy:

$ file github.ico
github.ico: MS Windows icon resource - 7 icons, 16x16, 32 bits/pixel, 24x24, 32 bits/pixel
$ sips -g pixelWidth -g hasAlpha github.ico
  pixelWidth: 256
  hasAlpha: yes
Enter fullscreen mode Exit fullscreen mode

Extracting the BMP entries and viewing them is the real test, because if you get the row order or channel order wrong, this is where you see it: an upside-down or blue-tinted icon.

I put the result into a small free tool, an SVG to ICO converter that runs entirely in the browser. It lets you pick sizes and switch between PNG and BMP entries, and it also outputs the 180×180 apple-touch-icon.png and the <link> tags. The encoder above is essentially all there is to it.

Top comments (0)