Skip to content

Commit cc41e0f

Browse files
committed
add guides on choosing ImageScript and coming from Jimp
1 parent d3ec573 commit cc41e0f

3 files changed

Lines changed: 279 additions & 0 deletions

File tree

‎guides/Choosing ImageScript.md‎

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
# Choosing ImageScript
2+
3+
ImageScript decodes, edits and encodes images in TypeScript, with no WebAssembly, no native binaries and no
4+
dependencies. This page says what that's good for, when another library is the better choice, and what you can rely on
5+
when you depend on it.
6+
7+
## When it fits
8+
9+
- **Where native libraries can't run:** Cloudflare Workers, Vercel's Edge Runtime, Deno Deploy and browsers. There is
10+
nothing to compile, download at install time or match to the platform.
11+
- **Where installs should stay small and simple:** one package of 2.6 MB on disk, no install scripts, the same files
12+
on every operating system and CPU.
13+
- **Generated images:** social cards, badges, charts, certificates, stickers and memes. It renders text with real
14+
fonts (shaping, right-to-left scripts, color emoji) and SVGs, and composites them with blend modes.
15+
- **Newer formats in plain JavaScript:** WebP, AVIF and JPEG XL, lossy and lossless, animated GIF, APNG and WebP, and
16+
HDR gain maps, all in both directions.
17+
18+
## When something else fits better
19+
20+
- **A busy Node.js server that only resizes photos:** [sharp](https://sharp.pixelplumbing.com) (libvips) is faster,
21+
about 4 times for JPEG decoding and encoding and for bicubic resizing in the
22+
[benchmark](https://github.com/imagescript/ImageScript/blob/master/bench/README.md), and it processes large images
23+
in pieces instead of holding them in memory. Use it where native modules install without trouble and throughput matters most.
24+
- **Code written for the Canvas API:** [@napi-rs/canvas](https://github.com/Brooooooklyn/canvas) or the browser's own
25+
canvas. ImageScript has its own API, not a canvas drawing context.
26+
- **Formats ImageScript doesn't read:** HEIC, RAW camera files, PDF, CCITT-compressed TIFF and arithmetic-coded JPEG.
27+
28+
## Where it's tested
29+
30+
Every change runs the full test suite on:
31+
32+
- Node.js 22.13, 24 and 26 on Linux, and Node.js 26 on macOS and Windows
33+
- Deno and Bun
34+
- Cloudflare's workerd (through Miniflare, with and without Node.js compatibility) and Vercel's Edge Runtime, bundled
35+
the way they are deployed
36+
- Chromium, bundled by Vite, with and without worker threads
37+
38+
The decoders are ports of the reference implementations (libjpeg, libwebp, dav1d, libjxl and jxl-oxide; HarfBuzz for
39+
text) and are compared with them: AVIF decodes exactly like dav1d, and WebP exactly like libwebp. Before major releases,
40+
thousands of real-world files are decoded and compared with Pillow and the reference decoders, and the decoders are
41+
fuzzed with damaged files.
42+
43+
## What you install
44+
45+
- No dependencies, and no install scripts.
46+
- Published from GitHub Actions with [npm provenance](https://docs.npmjs.com/generating-provenance-statements): npm
47+
shows which commit and workflow built each version. [JSR](https://jsr.io/@matmen/imagescript) gets each version
48+
from the same commit.
49+
- MIT licensed. The code ported from other projects keeps its credits in the README.
50+
51+
## Untrusted input
52+
53+
ImageScript is meant to handle images uploaded by anyone:
54+
55+
- Decoding refuses images larger than 16383 × 16383 pixels by default (`maxPixels`), checked before the pixels are
56+
decoded, and throws a `LimitError` you can catch. Animations count all their frames.
57+
- Cut-off files throw an error instead of returning an image padded with blank pixels. Damaged files either throw or
58+
are recovered the way the reference decoders recover them.
59+
- SVG and text rendering have their own limits (elements, layers, referenced images), and SVGs never fetch files or
60+
URLs: images and fonts are only used when you pass them in.
61+
62+
Report security problems privately, not in public issues: see the
63+
[security policy](https://github.com/imagescript/ImageScript/blob/master/SECURITY.md).
64+
65+
## Versions and support
66+
67+
ImageScript follows [semantic versioning](https://semver.org):
68+
69+
- **4.x makes no breaking changes.** Minor versions add features, patch versions fix bugs.
70+
- **Deprecation comes before removal.** When an API is replaced, the old one keeps working and is marked
71+
`@deprecated` (your editor shows it struck through, with the replacement), and it's removed in the next major
72+
version at the earliest. The release before a major already contains every replacement, so you can upgrade step by
73+
step: see [Migrating to 4.0](<./Migrating to 4.0.md>).
74+
- **The oldest supported Node.js version is only raised in a major version.** 4.x supports Node.js 22.13 and newer.
75+
- **Pixels can change in minor versions** when output gets better (a more accurate resize, a smaller encoded file).
76+
Don't compare encoded files byte for byte across versions; compare decoded pixels with a tolerance.

‎guides/Coming from Jimp.md‎

Lines changed: 201 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,201 @@
1+
# Coming from Jimp
2+
3+
ImageScript and Jimp solve the same problem the same way: images are decoded into an RGBA bitmap in JavaScript, edited
4+
in place and encoded again, with no native binaries. Most Jimp code translates line by line. This page maps Jimp 1.x
5+
calls to ImageScript 4.x, then lists what works differently and what Jimp has that ImageScript doesn't.
6+
7+
Every mapping below was checked by running both libraries on the same image (Jimp 1.6, ImageScript 4.0). Where the
8+
results aren't identical, the difference is described.
9+
10+
## Why switch
11+
12+
From the [benchmark](https://github.com/imagescript/ImageScript/blob/master/bench/README.md) (ImageScript 3.20.5 and
13+
Jimp 1.6.1 on a GitHub Actions runner, a 1920×1080 photo):
14+
15+
| | ImageScript | Jimp |
16+
|---|--:|--:|
17+
| decode JPEG | 62 ms | 168 ms |
18+
| encode JPEG (quality 80) | 81 ms | 429 ms |
19+
| encode PNG | 181 ms | 236 ms |
20+
| resize to half, bicubic | 46 ms | 195 ms |
21+
| rotate by 30° | 42 ms | 643 ms |
22+
| gaussian blur (radius 5) | 73 ms | 79 s |
23+
| brightness and contrast | 13 ms | 272 ms |
24+
| install size | 2.6 MB, 1 package | 26.8 MB, 64 packages |
25+
26+
Apart from speed:
27+
28+
- **Formats:** Jimp reads and writes PNG, JPEG, BMP, GIF and TIFF. ImageScript adds WebP, AVIF and JPEG XL (lossy and
29+
lossless), animated GIF, APNG and WebP, QOI, TGA, ICO and Netpbm, plus HDR gain maps. Jimp reads the first frame of an
30+
animated GIF; ImageScript decodes the whole {@link Animation}.
31+
- **Text:** Jimp prints with pre-rendered bitmap fonts (BMFont). ImageScript renders TrueType, OpenType and WOFF fonts at
32+
any size, with kerning, ligatures, right-to-left scripts and color emoji.
33+
- **SVG:** ImageScript renders SVGs ({@link Image.renderSVG}); Jimp doesn't.
34+
- **Runtimes:** ImageScript runs unchanged in Node.js, Deno, Bun, browsers and edge runtimes such as Cloudflare
35+
Workers. Jimp 1.6 can't be bundled for Workers: its package points bundlers that target browsers and Workers to a
36+
placeholder file without any exports.
37+
38+
## Reading and writing
39+
40+
Jimp reads files and URLs for you. ImageScript only takes bytes (an `ArrayBuffer`, `Uint8Array` or Node.js `Buffer`) and
41+
returns bytes, so the same code works without a file system.
42+
43+
```js
44+
// Jimp
45+
import { Jimp } from 'jimp';
46+
const image = await Jimp.read('input.jpg');
47+
await image.resize({ w: 256 }).write('output.png');
48+
49+
// ImageScript
50+
import { Image } from 'imagescript';
51+
import { readFile, writeFile } from 'node:fs/promises';
52+
const image = await Image.decode(await readFile('input.jpg'));
53+
await writeFile('output.png', await image.resize({ width: 256 }).encodePNG());
54+
```
55+
56+
| Jimp | ImageScript |
57+
|---|---|
58+
| `Jimp.read('file.png')` | `Image.decode(await readFile('file.png'))` |
59+
| `Jimp.read(url)` | `Image.decode(await (await fetch(url)).arrayBuffer())` |
60+
| `Jimp.fromBuffer(buffer)` | `Image.decode(buffer)` |
61+
| `new Jimp({ width, height, color })` | `new Image(width, height).fill(color)` (without `fill`, it's transparent) |
62+
| `image.write('out.png')` | `writeFile('out.png', await image.encodePNG())` |
63+
| `image.getBuffer('image/png')` | `image.encodePNG()` |
64+
| `image.getBuffer('image/jpeg', { quality: 80 })` | `image.encodeJPEG({ quality: 80 })` |
65+
| `image.getBase64('image/png')` | `'data:image/png;base64,' + Buffer.from(await image.encodePNG()).toString('base64')` |
66+
| `image.bitmap.width`, `.height` | `image.width`, `image.height` |
67+
| `image.bitmap.data` | `image.bitmap` (RGBA, four bytes per pixel, like Jimp's) |
68+
| `image.clone()` | `image.clone()` |
69+
70+
{@link Image.decode} gives the first frame of an animation; the global
71+
{@link decode} gives an `Animation` for animated files and an `Image` otherwise. Both apply the
72+
Exif orientation and convert embedded color profiles to sRGB by default.
73+
74+
## Resizing and cropping
75+
76+
| Jimp | ImageScript |
77+
|---|---|
78+
| `resize({ w: 200, h: 100 })` | `resize({ width: 200, height: 100 })` |
79+
| `resize({ w: 200 })` | `resize({ width: 200 })` (the height keeps the aspect ratio) |
80+
| `resize({ w, mode: ResizeStrategy.BICUBIC })` | `resize({ width, mode: 'bicubic' })` |
81+
| `resize({ w, mode: ResizeStrategy.NEAREST_NEIGHBOR })` | `resize({ width, mode: 'nearest-neighbor' })` |
82+
| `scale(0.5)` | `scale(0.5)` |
83+
| `scaleToFit({ w, h })` | `resize({ width, height, fit: 'inside' })` |
84+
| `cover({ w, h })` | `resize({ width, height, fit: 'cover' })` |
85+
| `contain({ w, h })` | `resize({ width, height, fit: 'contain' })` |
86+
| `crop({ x, y, w, h })` | `crop(x, y, w, h)` |
87+
| `autocrop()` | `trim()` |
88+
| `circle()` | `cropCircle()` |
89+
90+
Both resize bilinearly by default. ImageScript's other modes are `'bicubic'`, `'area'` (best for large reductions) and
91+
`'nearest-neighbor'`. `cover` and `contain` center the image; Jimp's `align` option has no equivalent, crop or composite
92+
yourself for other placements. `contain` fills the borders with transparency, or with `background: 0xffffffff`.
93+
94+
`crop()` changes the image in place, like Jimp's; {@link Image.extract | extract} returns the region as a new
95+
image and leaves the original as it is.
96+
97+
## Rotating and flipping
98+
99+
Jimp's `rotate()` turns counterclockwise, ImageScript's turns clockwise (like CSS), so negate the angle:
100+
101+
| Jimp | ImageScript |
102+
|---|---|
103+
| `rotate(90)` | `rotate(-90)` |
104+
| `rotate(30)` | `rotate(-30)` (both grow the image to fit; `expand: false` keeps the size) |
105+
| `flip({ horizontal: true })` | `flip('horizontal')` |
106+
| `flip({ vertical: true })` | `flip('vertical')` |
107+
| `flip({ horizontal: true, vertical: true })` | `rotate(180)` |
108+
109+
## Colors and filters
110+
111+
| Jimp | ImageScript |
112+
|---|---|
113+
| `brightness(1.2)` | `brightness(1.2)` (same factor) |
114+
| `contrast(v)` (-1 to 1) | `contrast((1 + v) / (1 - v))` (a factor, 1 keeps the image) |
115+
| `greyscale()` | `grayscale()` |
116+
| `invert()` | `invert()` |
117+
| `sepia()` | `sepia()` (a slightly different tone) |
118+
| `opacity(0.5)` | `opacity(0.5)` |
119+
| `fade(0.3)` | `opacity(0.7)` |
120+
| `blur(r)`, `gaussian(r)` | `blur(r)` |
121+
| `color([{ apply: 'hue', params: [90] }])` | `hueShift(90)` |
122+
| `quantize({ colors: 16 })` | `quantize({ colors: 16 })` |
123+
| `fisheye()` | `fisheye()` (the option is `strength`, not `radius`) |
124+
125+
`blur(r)` is a gaussian blur with `r` as its standard deviation, like CSS' `blur()`, and takes about as long at any
126+
radius. Its result is close to Jimp's `blur(r)`, which is about 10 times slower on a 1920×1080 photo; Jimp's
127+
`gaussian(r)` looks similar again and slows down with the square of the radius.
128+
129+
ImageScript's other adjustments: {@link Image.saturation | saturation},
130+
{@link Image.lightness | lightness}, {@link Image.gamma | gamma},
131+
{@link Image.sharpen | sharpen}, {@link Image.colorMatrix | colorMatrix},
132+
{@link Image.recolor | recolor}, {@link Image.dropShadow | dropShadow},
133+
{@link Image.outline | outline} and {@link Image.roundCorners | roundCorners}.
134+
135+
## Compositing
136+
137+
| Jimp | ImageScript |
138+
|---|---|
139+
| `composite(src, x, y)` | `composite(src, { x, y })` |
140+
| `composite(src, x, y, { opacitySource: 0.5 })` | `composite(src, { x, y, opacity: 0.5 })` |
141+
| `composite(src, x, y, { mode: BlendMode.MULTIPLY })` | `composite(src, { x, y, mode: 'multiply' })` |
142+
| `blit({ src, x, y, srcX, srcY, srcW, srcH })` | `composite(src.extract(srcX, srcY, srcW, srcH), { x, y })` |
143+
144+
Blend modes are CSS' names: `'multiply'`, `'screen'`, `'overlay'`, `'darken'`, `'lighten'`, `'color-dodge'`,
145+
`'color-burn'`, `'hard-light'`, `'soft-light'`, `'difference'`, `'exclusion'`, and `'add'`.
146+
147+
## Text
148+
149+
Jimp's `print()` draws with a bitmap font loaded by `loadFont()`. ImageScript renders the text into an image of its own,
150+
which you then place with `composite()`:
151+
152+
```js
153+
// Jimp
154+
import { Jimp, loadFont } from 'jimp';
155+
import { SANS_32_BLACK } from 'jimp/fonts';
156+
const font = await loadFont(SANS_32_BLACK);
157+
image.print({ font, x: 10, y: 10, text: 'Hello', maxWidth: 300 });
158+
159+
// ImageScript
160+
const font = await readFile('Inter-Regular.ttf');
161+
const text = await Image.renderText('Hello', { font, size: 32, color: 0x000000ff, width: 300 });
162+
image.composite(text, { x: 10, y: 10 });
163+
```
164+
165+
With `width`, the text wraps; `horizontalAlign` and `verticalAlign` place it in the box. The font is any TrueType,
166+
OpenType or WOFF file; pass several (`font: [text, emoji]`) to fall back to the next one for characters the first one
167+
lacks.
168+
169+
## Pixels
170+
171+
Both use the same color format: a 32-bit number `0xRRGGBBAA`.
172+
173+
| Jimp | ImageScript |
174+
|---|---|
175+
| `getPixelColor(x, y)` | `getPixelAt(x, y)` |
176+
| `setPixelColor(color, x, y)` | `setPixelAt(x, y, color)` (the color comes last) |
177+
| `scan(x, y, w, h, (x, y, idx) => ...)` | `for (const [x, y, color] of image.pixels())`, or index `image.bitmap` directly |
178+
| `intToRGBA(color)` (`{ r, g, b, a }`) | `Colors.toRGBA(color)` (`[r, g, b, a]`) |
179+
| `rgbaToInt(r, g, b, a)` | `Colors.fromRGBA(r, g, b, a)` |
180+
181+
Coordinates start at 0 in both. For speed, work on `image.bitmap` directly: the pixel at `(x, y)` starts at
182+
`(y * image.width + x) * 4`.
183+
184+
## What ImageScript doesn't have
185+
186+
These Jimp features have no counterpart. Where there is a short replacement, it's given.
187+
188+
- `mask()`: no replacement.
189+
- `threshold()`, `posterize()`, `normalize()`, `dither()`, `convolute()` and `convolution()` (custom kernels): no
190+
replacement; loop over `image.bitmap` for these.
191+
- `pixelate()`: resize down with `mode: 'area'`, then back up with `mode: 'nearest-neighbor'`. The blocks are averaged
192+
like Jimp's, but they don't line up with Jimp's exactly.
193+
- `hash()`, `pHash()`, `distance()` and `diff()` (image comparison): no replacement.
194+
- `displace()`: no replacement.
195+
- The `color()` actions other than `hue`: `saturate` and `desaturate` are close to
196+
{@link Image.saturation | saturation}, `mix`, `tint` and `shade` to compositing a filled image with
197+
`opacity`.
198+
- Reading from file paths and URLs: read the bytes yourself, as shown above.
199+
200+
If you need one of these, [open an issue](https://github.com/imagescript/ImageScript/issues): what people ask for is
201+
what gets added.

‎src/index.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
/**
22
* @packageDocumentation
3+
* @document ../guides/Choosing ImageScript.md
4+
* @document ../guides/Coming from Jimp.md
35
* @document ../guides/Migrating to 4.0.md
46
*/
57
// (the guide is attached to the entry module: as a project document it turned the docs into a module "index", every

0 commit comments

Comments
 (0)