Skip to content

Commit ab6a974

Browse files
committed
add guides on shrinking images before upload and generating favicons
1 parent 479d78b commit ab6a974

4 files changed

Lines changed: 238 additions & 0 deletions

File tree

‎guides/Generate favicons.md‎

Lines changed: 122 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,122 @@
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+
![The generated icons: favicon.ico with its three sizes, the apple-touch-icon, icon-192, icon-512 and the maskable icon](./favicons-example.png)
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.
Lines changed: 114 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,114 @@
1+
---
2+
group: Examples
3+
---
4+
5+
# Shrink images before upload
6+
7+
A phone photo is 3 to 6 MB, and the server usually wants a fraction of that. Shrinking the image in the browser before
8+
it is uploaded saves bandwidth, and on a slow connection it saves the user's time. The browser's own way is a canvas:
9+
draw the image on it, scale it, call `canvas.toBlob()`. ImageScript does the same in plain TypeScript, and the page
10+
below is all it takes:
11+
12+
```html
13+
<!doctype html>
14+
<meta charset="utf-8">
15+
<input type="file" id="file" accept="image/*">
16+
<p id="info"></p>
17+
<img id="preview" alt="" style="max-width: 100%">
18+
19+
<script type="module">
20+
import { Image, LimitError } from 'https://cdn.jsdelivr.net/npm/imagescript@4/+esm';
21+
22+
// the image's longest side becomes at most `maxSize` pixels; the result is a WebP file
23+
async function shrink(file, { maxSize = 1600, quality = 80 } = {}) {
24+
const image = await Image.decode(await file.arrayBuffer()); // turns the picture upright, as the Exif data says
25+
if (Math.max(image.width, image.height) > maxSize) {
26+
image.resize({ width: maxSize, height: maxSize, fit: 'inside' });
27+
}
28+
return new Blob([await image.encodeWebP({ quality })], { type: 'image/webp' });
29+
}
30+
31+
const kilobytes = (bytes) => `${Math.round(bytes / 1000)} kB`;
32+
const info = document.getElementById('info');
33+
const preview = document.getElementById('preview');
34+
35+
document.getElementById('file').addEventListener('change', async (event) => {
36+
const [file] = event.target.files;
37+
if (!file) return;
38+
info.textContent = 'Shrinking…';
39+
try {
40+
const blob = await shrink(file);
41+
info.textContent = `${kilobytes(file.size)} → ${kilobytes(blob.size)}`;
42+
preview.src = URL.createObjectURL(blob);
43+
// await fetch('/upload', { method: 'POST', body: blob });
44+
} catch (error) {
45+
info.textContent = error instanceof LimitError ? 'That image is too large.' : `Can't read that image: ${error.message}`;
46+
}
47+
});
48+
</script>
49+
```
50+
51+
Save it as an `.html` file and open it from a web server (the browser doesn't run modules from `file://`). Choosing a
52+
photo shows the size before and after and the result; the commented `fetch()` is where the upload goes.
53+
54+
## What you get
55+
56+
- **The same file in every browser.** `canvas.toBlob(callback, 'image/jpeg', 0.8)` runs the browser's own encoder, and
57+
the encoders differ: for the same photo the JPEG was 246 kB in Chromium, 280 kB in Firefox and 286 kB in Safari's
58+
engine. ImageScript makes the same bytes everywhere (234 kB), so a quality setting means the same thing for every
59+
user, and you can test it once.
60+
- **Formats the browser can't encode.** Asking a canvas for `'image/avif'` gives a PNG instead, in Chromium, Firefox
61+
and WebKit, without an error: a 3.3 MB photo came back as a PNG of 2.9 to 3.8 MB, depending on the browser. ImageScript encodes AVIF and JPEG XL as well
62+
as WebP and JPEG, though AVIF takes several seconds for a photo, so it suits a worker or a server better.
63+
- **Metadata that stays out.** The result carries none of the photo's Exif data (location, camera, time). The only
64+
metadata is the name of the software, `ImageScript`, which `metadata: { software: null }` leaves out.
65+
- **Limits that protect the page.** A file whose pixels would not fit in memory throws a `LimitError` before it is
66+
decoded (`maxPixels`, 16383 × 16383 by default), so an enormous image can't freeze the tab.
67+
68+
## Keeping the page responsive
69+
70+
Decoding, resizing and encoding a 12-megapixel photo takes about a second of CPU time on a desktop (longer on a phone),
71+
and the page above does it on the main thread, so it stops reacting for that long. For anything beyond a demo, run the
72+
work in a worker, as below. The script is about 1.05 MB (438 kB compressed) and the browser keeps it after the first visit.
73+
74+
## In a worker
75+
76+
With a bundler (Vite, webpack, esbuild), the work moves off the main thread:
77+
78+
```js
79+
// shrink.worker.js
80+
import { Image } from 'imagescript';
81+
82+
self.onmessage = async ({ data: { buffer, maxSize, quality } }) => {
83+
const image = await Image.decode(buffer);
84+
if (Math.max(image.width, image.height) > maxSize) {
85+
image.resize({ width: maxSize, height: maxSize, fit: 'inside' });
86+
}
87+
const bytes = await image.encodeWebP({ quality });
88+
self.postMessage(bytes, [bytes.buffer]);
89+
};
90+
```
91+
92+
```js
93+
// in the page
94+
const worker = new Worker(new URL('./shrink.worker.js', import.meta.url), { type: 'module' });
95+
96+
function shrink(file, maxSize = 1600, quality = 80) {
97+
return new Promise(async (resolve, reject) => {
98+
worker.onmessage = ({ data }) => resolve(new Blob([data], { type: 'image/webp' }));
99+
worker.onerror = reject;
100+
const buffer = await file.arrayBuffer();
101+
worker.postMessage({ buffer, maxSize, quality }, [buffer]);
102+
});
103+
}
104+
```
105+
106+
A page that is [cross-origin isolated](https://developer.mozilla.org/docs/Web/API/Window/crossOriginIsolated) also
107+
lets the AVIF and lossless WebP encoders use several threads (the `threads` option): a photo like the one above takes
108+
3 to 4 seconds as AVIF with threads, and 6 to 16 seconds without.
109+
110+
## Pictures that aren't stills
111+
112+
An animated GIF or WebP isn't a single image: `Image.decode()` takes its first frame. To keep the animation, leave
113+
such files as they are (`if (file.type === 'image/gif') return file;`) or use {@link decode}, which returns an
114+
{@link Animation} for them, and encode the frames again.

‎guides/favicons-example.png‎

38 KB
Loading

‎src/index.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22
* @packageDocumentation
33
* @document ../guides/Choosing ImageScript.md
44
* @document ../guides/Coming from Jimp.md
5+
* @document ../guides/Generate favicons.md
6+
* @document ../guides/Shrink images before upload.md
57
* @document ../guides/Social cards for static sites.md
68
* @document ../guides/Migrating to 4.0.md
79
*/

0 commit comments

Comments
 (0)