Skip to content

Commit 0eb1662

Browse files
committed
address the second user report: pixels(), still durations, inspect and docs
1 parent 7790b27 commit 0eb1662

7 files changed

Lines changed: 64 additions & 11 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -128,6 +128,10 @@ Upgrading from 3.x? Upgrade to the latest 3.x release first, fix the deprecation
128128

129129
### Fixes
130130

131+
- **Cut-off JPEG and lossy WebP files throw** like the other formats: a JPEG without any scan data, or whose scan ends before its last block, and a WebP whose partitions end early. They decoded without an error, as gray or smeared images. A JPEG that only lacks its end marker still decodes.
132+
- `Image.pixels()` yields the pixels the image had when the iteration started, where resizing the image meanwhile threw an error from the inside or stopped early.
133+
- `Animation.decode()` gives a still image (PNG, JPEG XL, WebP, JPEG, ...) a frame of 100 ms, the `Frame` default, not 0 ms.
134+
- `JSON.stringify()` and `console.log()` of an `Image`, `Frame` or `Animation` show their size (and duration), not every pixel; `new Colors()` throws.
131135
- `image.composite(image, { x, y })` onto itself (or an image sharing its pixels) read pixels it had already overwritten, and differed from compositing a copy.
132136
- `dominantColor({ threshold })` outside 0-256, `GainMap.encodeJPEG({ quality: 0 })` and a `metadata` that is not an object throw instead of being clamped or ignored.
133137
- `Animation.resize()` changes a frame once when the animation lists the same `Frame` (or two frames share one `Image`) more than once, as a hold or a ping-pong does; each listing resized or moved it again before (`new Animation([f, f, f]).resize(50, 50)` made 13x13 frames).

‎README.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@
1616
**ImageScript** decodes, edits and encodes images in pure TypeScript: no WebAssembly, no native binaries, and no
1717
runtime dependencies. It runs in Node.js 22.13+, Deno, Bun, browsers and edge runtimes (Cloudflare Workers, Vercel's
1818
Edge Runtime, Deno Deploy), works with `import` and, on supported Node.js versions, `require()`, and ships with type
19-
definitions (TypeScript 5.7 or newer: with older versions and `skipLibCheck`, the encoders' return types become `any`). Large AVIF and JPEG XL operations, and lossless WebP encoding, can use multiple CPU cores when the runtime
19+
definitions (TypeScript 5.7 or newer; CommonJS projects with `module: nodenext` need 5.8 or newer to `import` it. With older versions and `skipLibCheck`, the encoders' return types become `any`). Large AVIF and JPEG XL operations, and lossless WebP encoding, can use multiple CPU cores when the runtime
2020
supports it.
2121

2222
```sh

‎src/animation.ts‎

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ import { resolveMetadata, pngText, exifData, gifComments } from './metadata.ts';
1515
import { checkOptions, oneOf, pixelLimit, checkThreads, finite, compressionLevel, loopCount, toPlays, fromPlays, fitLoops, fitDuration, maxDuration, color as checkColor } from './util/options.ts';
1616
import { MAX_PIXELS, decoding, checkPixels } from './util/limits.ts';
1717
import { AnimationEncoder } from './animation-encoder.ts';
18+
import { describe } from './util/inspect.ts';
1819

1920
// frames decoded fully composited, as full canvas frames
2021
function canvasFrames(width: number, height: number, frames: Array<{ pixels: Uint8Array | Uint8ClampedArray, duration: number }>): Frame[] {
@@ -707,7 +708,8 @@ export class Animation {
707708
* const animation = await Animation.decode(gifBytes);
708709
* const webp = await animation.resize({ width: 320 }).encodeWebP({ quality: 75 });
709710
* ```
710-
* @remarks An AVIF image sequence is decoded as its first frame only
711+
* @remarks A still image becomes one frame of 100 ms, the {@link Frame} default. An AVIF image sequence is decoded as
712+
* its first frame only
711713
* @param input The binary data to decode
712714
* @param options See {@link DecodeOptions}
713715
* @throws {@link LimitError} if the frames have more than `options.maxPixels` pixels together
@@ -756,13 +758,15 @@ export class Animation {
756758
const frames = orient(profile(canvasFrames(decoded.width, decoded.height, webp.composite(decoded)), decoded.icc), decoded.orientation);
757759
const animation = new Animation(frames, { loopCount: fromPlays(decoded.loopCount), width: frames[0]?.width ?? decoded.width, height: frames[0]?.height ?? decoded.height });
758760
animation.__animationSignal__ = animated;
761+
// (a still image has no duration: the frame's default)
762+
if (!animated) for (const frame of frames) frame.duration = 100;
759763
return animation;
760764
}
761765

762766
// (still PNGs decode like images)
763767
if (type === 'png' && !png.isAnimated(data)) {
764768
const image = await Image.decode(data, { maxPixels, applyOrientation, applyColorProfile });
765-
return new Animation(canvasFrames(image.width, image.height, [{ pixels: image.bitmap, duration: 0 }]), { loopCount: Infinity, width: image.width, height: image.height });
769+
return new Animation(canvasFrames(image.width, image.height, [{ pixels: image.bitmap, duration: 100 }]), { loopCount: Infinity, width: image.width, height: image.height });
766770
}
767771
if (type === 'png') {
768772
const decoded = await png.decodeAnimation(data, false, maxPixels);
@@ -809,12 +813,14 @@ export class Animation {
809813
}
810814
const animation = new Animation(frames, { loopCount: animated ? loops : Infinity, ...(frames.length ? { width: frames[0].width, height: frames[0].height } : {}) });
811815
animation.__animationSignal__ = animated;
816+
// (a still image has no duration: the frame's default)
817+
if (!animated) for (const frame of frames) frame.duration = 100;
812818
return animation;
813819
}
814820

815821
if (type) {
816822
const image = await Image.decode(data, { maxPixels, applyOrientation, applyColorProfile, toneMapping, gainMap, threads });
817-
return new Animation([new Frame(image, { duration: 0 })], { width: image.width, height: image.height });
823+
return new Animation([new Frame(image)], { width: image.width, height: image.height });
818824
}
819825
throw new Error('Unsupported image type');
820826
}
@@ -837,3 +843,5 @@ function canvasSize(width: number, height: number): [width: number, height: numb
837843
if (!Number.isInteger(width) || !Number.isInteger(height) || width < 1 || height < 1) throw new RangeError(`Invalid canvas size: ${width}x${height}`);
838844
return [width, height];
839845
}
846+
847+
describe(Animation, animation => ({ width: animation.width, height: animation.height, duration: animation.duration, frames: animation.frames.length }));

‎src/colors.ts‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -95,7 +95,9 @@ function gradientBetween(startColor: Color, endColor: Color): (position: number)
9595
* and return, and gradients between colors
9696
*/
9797
export class Colors {
98-
private constructor() {}
98+
private constructor() {
99+
throw new TypeError('Colors only has static methods, like Colors.fromRGBA()');
100+
}
99101

100102
/**
101103
* Converts RGBA components to an RGBA value, values are rounded and clamped to 0..255
@@ -204,6 +206,9 @@ export class Colors {
204206
* Creates a multi-point gradient generator
205207
* @param stops The colors along the gradient: their positions (0..1) and colors (`{ 0: 0xff0000ff, 1: 0x00ff00ff }`),
206208
* or just the colors, evenly spaced (`[0xff0000ff, 0x00ff00ff]`), like {@link GradientOptions.stops}
209+
* @remarks A stop may lie outside 0..1 (`{ 0: red, 2: blue }`): it is where it says, so the part between 0 and 1
210+
* shows only part of the way between its colors. Before the first stop and after the last one, the gradient has
211+
* their colors
207212
* @return The gradient generator. The function argument is the position in the gradient (0..1).
208213
*/
209214
static gradient(stops: Record<number, Color> | Color[]): (position: number) => Color {

‎src/frame.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { Image, ResizeOptions, ResizeToOptions, TrimOptions, RotateOptions, TransformOptions, AffineTransform, ShadowOptions, OutlineOptions } from './image.ts';
22
import { checkOptions, finite, oneOf } from './util/options.ts';
3+
import { describe } from './util/inspect.ts';
34

45
/**
56
* What happens to a frame's area before the next frame is drawn, see {@link Frame.disposalMode}:
@@ -298,3 +299,5 @@ export class Frame {
298299
return this.__tracked__(image => image.outline(options));
299300
}
300301
}
302+
303+
describe(Frame, frame => ({ width: frame.width, height: frame.height, duration: frame.duration }));

‎src/image.ts‎

Lines changed: 17 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@ import { multiply, invert } from './util/matrix.ts';
3737
import { sampleAffine } from './util/affine.ts';
3838
import { rotateBilinear } from './util/rotate.ts';
3939
import * as gainMapCodec from './codecs/gainmap.ts';
40+
import { describe } from './util/inspect.ts';
4041

4142
/** A color as a 32-bit RGBA integer (`0xRRGGBBAA`) */
4243
export type Color = number;
@@ -312,7 +313,8 @@ export interface OutlineOptions {
312313
export interface GradientOptions {
313314
/**
314315
* The colors along the gradient: their positions (0..1) and colors (`{ 0: 0xff0000ff, 0.5: 0xffff00ff, 1: 0x00ff00ff }`),
315-
* or just the colors, evenly spaced (`[0xff0000ff, 0x00ff00ff]`), like {@link Colors.gradient} takes them
316+
* or just the colors, evenly spaced (`[0xff0000ff, 0x00ff00ff]`), like {@link Colors.gradient} takes them. A
317+
* position outside 0..1 is allowed, see {@link Colors.gradient}
316318
*/
317319
stops: Record<number, Color> | Color[];
318320
}
@@ -848,6 +850,9 @@ function featureList(features: Record<string, boolean | number>): Array<[string,
848850
/**
849851
* An RGBA image; provides the codecs and the manipulation functions. Methods that change the image modify it in place
850852
* and return it, so calls can be chained
853+
*
854+
* @remarks Subclassing is not supported: the methods that make an image ({@link Image.clone}, {@link Image.extract},
855+
* {@link Image.decode}, ...) return plain `Image`s, without calling a subclass' constructor
851856
*/
852857
export class Image {
853858
/**
@@ -885,7 +890,8 @@ export class Image {
885890
* Creates a new image with the given dimensions, all pixels transparent black
886891
* @param width The width in pixels
887892
* @param height The height in pixels
888-
* @throws `RangeError` if the width or height is not a number of at least 1, or the image is too large to allocate
893+
* @throws `TypeError` if the width or height is not a number
894+
* @throws `RangeError` if the width or height is less than 1, or the image is too large to allocate
889895
*/
890896
constructor(width: number, height: number) {
891897
width = Math.trunc(finite(width, 'width'));
@@ -984,14 +990,17 @@ export class Image {
984990
}
985991

986992
/**
987-
* Yields an [x, y, color] array for every pixel in the image (0-based), row by row
993+
* Yields an [x, y, color] array for every pixel in the image (0-based), row by row. The pixels are those the image
994+
* had when the iteration started: changing the image meanwhile (even its size) doesn't affect them
988995
* @yields The coordinates and color of the pixel ([x, y, color])
989996
*/
990997
*pixels(): Generator<[x: number, y: number, color: Color], void, undefined> {
998+
// (the pixels as they are now: resizing the image meanwhile doesn't change what this yields)
991999
const view = new DataView(this.bitmap.buffer, this.bitmap.byteOffset, this.bitmap.byteLength);
1000+
const width = this.width, height = this.height;
9921001
let offset = 0;
993-
for (let y = 0; y < this.height; y++)
994-
for (let x = 0; x < this.width; x++, offset += 4)
1002+
for (let y = 0; y < height; y++)
1003+
for (let x = 0; x < width; x++, offset += 4)
9951004
yield [x, y, view.getUint32(offset, false)];
9961005
}
9971006

@@ -2661,7 +2670,7 @@ export class Image {
26612670

26622671
/**
26632672
* Encodes the image into a PNG, with the smallest lossless color type (a palette for up to 256 colors,
2664-
* grayscale or RGB, alpha only if needed). Uses the runtime's native zlib when available
2673+
* grayscale or RGB, alpha only if needed). Uses the runtime's native zlib when available (the files differ between runtimes, whose zlibs compress differently: about a quarter larger on Deno than on Node and Bun)
26652674
* @param options See {@link PNGEncodeOptions}
26662675
* @return The encoded data
26672676
*/
@@ -3409,3 +3418,5 @@ function distanceTransform(f: Float64Array, n: number, d: Float64Array, v: Int32
34093418
nearest[q] = v[j];
34103419
}
34113420
}
3421+
3422+
describe(Image, image => ({ width: image.width, height: image.height }));

‎src/util/inspect.ts‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
/**
2+
* Gives a class a short form for `console.log()` (Node's `util.inspect`, Bun and Deno use the same symbol) and for
3+
* `JSON.stringify()`: the class' `toString()` and a few fields, not the pixels (an image of 12 megapixels would write
4+
* 12 million keys). Done to the prototype: a method with a symbol as its name can't be declared in a class body
5+
* @internal
6+
*/
7+
export function describe<T extends object>(type: new (...args: never[]) => T, json: (value: T) => object): void {
8+
Object.defineProperty(type.prototype, Symbol.for('nodejs.util.inspect.custom'), {
9+
value(this: T): string {
10+
return (this as { toString(): string }).toString();
11+
},
12+
writable: true,
13+
configurable: true
14+
});
15+
Object.defineProperty(type.prototype, 'toJSON', {
16+
value(this: T): object {
17+
return json(this);
18+
},
19+
writable: true,
20+
configurable: true
21+
});
22+
}

0 commit comments

Comments
 (0)