|
| 1 | +--- |
| 2 | +group: Examples |
| 3 | +--- |
| 4 | + |
| 5 | +# Generate favicons |
| 6 | + |
| 7 | +A site needs a handful of icons: one for the browser tab, one for iOS' home screen, and a few for the web app manifest. |
| 8 | +One script makes them all from your logo, as an SVG or a square PNG, and the logo's SVG doubles as the modern favicon. |
| 9 | + |
| 10 | + |
| 11 | + |
| 12 | +## The script |
| 13 | + |
| 14 | +Save it as `favicons.mjs` and run `node favicons.mjs logo.svg public '#141821'`. The last argument is the background |
| 15 | +color of the icons that can't be transparent (a six-digit hex color, white by default). |
| 16 | + |
| 17 | +```js |
| 18 | +// node favicons.mjs <logo.svg or logo.png> [output directory] [background color] |
| 19 | +// Writes the icons a website needs from one logo: favicon.ico, icon.svg (for an SVG logo), apple-touch-icon.png, |
| 20 | +// icon-192.png, icon-512.png and icon-maskable-512.png |
| 21 | +import { copyFile, mkdir, readFile, writeFile } from 'node:fs/promises'; |
| 22 | +import { Image } from 'imagescript'; |
| 23 | + |
| 24 | +const [source, outDir = 'public', background = '#ffffff'] = process.argv.slice(2); |
| 25 | +if (!source) throw new Error('Usage: node favicons.mjs <logo.svg or logo.png> [output directory] [background color]'); |
| 26 | +const backgroundColor = Number.parseInt(background.replace('#', '') + 'ff', 16); // '#141821' -> 0x141821ff |
| 27 | + |
| 28 | +const bytes = await readFile(source); |
| 29 | +const isSVG = source.toLowerCase().endsWith('.svg'); |
| 30 | +const png = isSVG ? null : await Image.decode(bytes); |
| 31 | +if (png && (png.width !== png.height || png.width < 512)) throw new Error('A PNG logo has to be square and at least 512 pixels'); |
| 32 | + |
| 33 | +// the logo at a size, with a transparent background |
| 34 | +const logo = async (size) => isSVG |
| 35 | + ? Image.renderSVG(bytes, { width: size }) |
| 36 | + : png.clone().resize({ width: size, height: size, mode: 'area' }); |
| 37 | + |
| 38 | +// the logo on a solid background, with an empty margin around it (a share of the size) |
| 39 | +async function onBackground(size, margin = 0) { |
| 40 | + const inner = Math.round(size * (1 - margin * 2)); |
| 41 | + return new Image(size, size).fill(backgroundColor).composite(await logo(inner), { x: Math.round((size - inner) / 2), y: Math.round((size - inner) / 2) }); |
| 42 | +} |
| 43 | + |
| 44 | +// favicon.ico: a small header, then the images: modern browsers and Windows read PNG files inside it |
| 45 | +function ico(images) { |
| 46 | + const total = images.reduce((sum, { bytes }) => sum + bytes.length, 0); |
| 47 | + const out = new Uint8Array(6 + 16 * images.length + total); |
| 48 | + const view = new DataView(out.buffer); |
| 49 | + view.setUint16(2, 1, true); // type: icon |
| 50 | + view.setUint16(4, images.length, true); |
| 51 | + let offset = 6 + 16 * images.length; |
| 52 | + images.forEach(({ size, bytes }, i) => { |
| 53 | + const entry = 6 + 16 * i; |
| 54 | + out[entry] = size; // width and height in pixels (0 would mean 256) |
| 55 | + out[entry + 1] = size; |
| 56 | + view.setUint16(entry + 4, 1, true); // color planes |
| 57 | + view.setUint16(entry + 6, 32, true); // bits per pixel |
| 58 | + view.setUint32(entry + 8, bytes.length, true); |
| 59 | + view.setUint32(entry + 12, offset, true); |
| 60 | + out.set(bytes, offset); |
| 61 | + offset += bytes.length; |
| 62 | + }); |
| 63 | + return out; |
| 64 | +} |
| 65 | + |
| 66 | +await mkdir(outDir, { recursive: true }); |
| 67 | +const write = async (name, data) => { await writeFile(`${outDir}/${name}`, data); console.log('wrote', `${outDir}/${name}`); }; |
| 68 | + |
| 69 | +await write('favicon.ico', ico(await Promise.all([16, 32, 48].map(async (size) => ({ size, bytes: await (await logo(size)).encodePNG() }))))); |
| 70 | +if (isSVG) { await copyFile(source, `${outDir}/icon.svg`); console.log('wrote', `${outDir}/icon.svg`); } |
| 71 | +await write('apple-touch-icon.png', await (await onBackground(180)).encodePNG()); // iOS paints transparency black |
| 72 | +await write('icon-192.png', await (await logo(192)).encodePNG()); |
| 73 | +await write('icon-512.png', await (await logo(512)).encodePNG()); |
| 74 | +await write('icon-maskable-512.png', await (await onBackground(512, 0.1)).encodePNG()); // Android may cut the outer 10% off |
| 75 | +``` |
| 76 | + |
| 77 | +It writes these files into the directory: |
| 78 | + |
| 79 | +- `favicon.ico` with images of 16, 32 and 48 pixels. ImageScript doesn't write `.ico` files, but an `.ico` file is a |
| 80 | + short header followed by PNG images, and the script writes the header itself. |
| 81 | +- `icon.svg`, a copy of an SVG logo, which browsers scale to any size. |
| 82 | +- `apple-touch-icon.png`, 180 pixels. iOS paints transparent pixels black, so it gets the background color. |
| 83 | +- `icon-192.png` and `icon-512.png` for the web app manifest. |
| 84 | +- `icon-maskable-512.png`, with the logo inside the inner 80 percent on the background color: Android may crop the |
| 85 | + icon to a circle or a rounded square. |
| 86 | + |
| 87 | +The whole run takes about half a second. A PNG logo has to be square and at least 512 pixels, since the icons are made |
| 88 | +by shrinking it. |
| 89 | + |
| 90 | +## Using the icons |
| 91 | + |
| 92 | +Put these in the `<head>` of every page: |
| 93 | + |
| 94 | +```html |
| 95 | +<link rel="icon" href="/favicon.ico" sizes="32x32"> |
| 96 | +<link rel="icon" href="/icon.svg" type="image/svg+xml"> |
| 97 | +<link rel="apple-touch-icon" href="/apple-touch-icon.png"> |
| 98 | +<link rel="manifest" href="/manifest.webmanifest"> |
| 99 | +``` |
| 100 | + |
| 101 | +and this in `manifest.webmanifest`: |
| 102 | + |
| 103 | +```json |
| 104 | +{ |
| 105 | + "name": "Example", |
| 106 | + "icons": [ |
| 107 | + { "src": "/icon-192.png", "type": "image/png", "sizes": "192x192" }, |
| 108 | + { "src": "/icon-512.png", "type": "image/png", "sizes": "512x512" }, |
| 109 | + { "src": "/icon-maskable-512.png", "type": "image/png", "sizes": "512x512", "purpose": "maskable" } |
| 110 | + ] |
| 111 | +} |
| 112 | +``` |
| 113 | + |
| 114 | +## Notes |
| 115 | + |
| 116 | +- **Small sizes need their own drawing.** A logo with fine detail turns to mush at 16 pixels. Give the script a simpler |
| 117 | + SVG for the icon (the mark without the wordmark, thicker strokes) than the one on your pages. |
| 118 | +- **SVG favicons can follow the dark mode.** An SVG with a `<style>` block and `@media (prefers-color-scheme: dark)` |
| 119 | + changes its colors with the browser's theme; the PNG files don't. |
| 120 | +- **Fonts in an SVG logo.** ImageScript doesn't use the fonts installed on a machine: text in an SVG is only drawn with |
| 121 | + a font you pass in the `font` option of {@link Image.renderSVG}, and not at all without one. Convert the text to paths |
| 122 | + in your editor before you use the logo here. |
0 commit comments