Skip to content

bitmap ​

Bitmaps: load, draw, composite and save images.

Import

ts
import { BitmapFormat, BlendMode, ScaleFilter, LineCap, ... } from "bitmap";

BitmapFormat enum ​

ts
enum BitmapFormat

Pixel format identifier for Bitmap allocation and conversion.

  • BitmapFormat.RGB8: 24-bit RGB, no alpha. 3 bytes per pixel.
  • BitmapFormat.RGBA8: 32-bit RGBA. 4 bytes per pixel. The default.
  • BitmapFormat.RGB16: 48-bit RGB, no alpha. 6 bytes per pixel.
  • BitmapFormat.RGBA16: 64-bit RGBA. 8 bytes per pixel.

BlendMode enum ​

ts
enum BlendMode

Compositing operator for Bitmap.composite, DrawContext.setBlendMode, and Bitmap.drawScaled.

  • BlendMode.REPLACE: Direct overwrite. Source replaces destination unconditionally.
  • BlendMode.ALPHA: Standard alpha compositing. Source alpha blends over destination.
  • BlendMode.ADDITIVE: Add channels: dest + src. Saturates at 255.
  • BlendMode.MULTIPLY: Multiply channels: dest * src / 255.
  • BlendMode.SCREEN: Inverse multiply: 255 - ((255-dest) * (255-src) / 255).
  • BlendMode.OVERLAY: Combination of multiply and screen depending on dest brightness.
  • BlendMode.DARKEN: Per-channel min(dest, src).
  • BlendMode.LIGHTEN: Per-channel max(dest, src).
  • BlendMode.COLOR_DODGE: Brighten dest by src; high src values produce extreme highlights.
  • BlendMode.COLOR_BURN: Darken dest by src; high src values produce deep shadows.
  • BlendMode.DIFFERENCE: Absolute difference between channels.
  • BlendMode.EXCLUSION: Like difference but lower contrast.

ScaleFilter enum ​

ts
enum ScaleFilter

Sampling filter for Bitmap.resize and Bitmap.drawScaled.

  • ScaleFilter.NEAREST: Nearest-neighbour. Fastest, blocky output, preserves hard edges.
  • ScaleFilter.BILINEAR: Bilinear interpolation. Smooth but soft. The default.
  • ScaleFilter.BICUBIC: Bicubic interpolation. Sharpest of the smooth filters, slowest.

LineCap enum ​

ts
enum LineCap

Line-end style for DrawContext.setLineCap.

  • LineCap.BUTT: Flat end at the line endpoint. The default.
  • LineCap.ROUND: Semicircular cap extending past the endpoint by half the line width.
  • LineCap.SQUARE: Square cap extending past the endpoint by half the line width.

LineJoin enum ​

ts
enum LineJoin

Line-join style for DrawContext.setLineJoin.

  • LineJoin.MITER: Sharp mitered corner. The default.
  • LineJoin.ROUND: Rounded corner with radius equal to half the line width.
  • LineJoin.BEVEL: Beveled corner: a straight edge between the two segments.

TextAlign enum ​

ts
enum TextAlign

Horizontal text alignment for DrawContext.setTextAlign.

  • TextAlign.LEFT: Anchor on the left edge of the text bounding box. The default.
  • TextAlign.CENTER: Anchor on the horizontal center.
  • TextAlign.RIGHT: Anchor on the right edge.

TextBaseline enum ​

ts
enum TextBaseline

Vertical text alignment for DrawContext.setTextBaseline.

  • TextBaseline.ALPHABETIC: Anchor on the alphabetic baseline. The default.
  • TextBaseline.TOP: Anchor on the top of the text bounding box.
  • TextBaseline.MIDDLE: Anchor on the vertical center of the text bounding box.
  • TextBaseline.BOTTOM: Anchor on the bottom of the text bounding box.

ImageFormat enum ​

ts
enum ImageFormat

File format for Bitmap.encode.

  • ImageFormat.PNG: Portable Network Graphics. Lossless.
  • ImageFormat.JPEG: JPEG. Lossy, no alpha channel.
  • ImageFormat.BMP: Windows BMP. Lossless, uncompressed.
  • ImageFormat.TGA: Truevision TGA. Lossless.
  • ImageFormat.WEBP: WebP. Lossy or lossless, smaller than PNG/JPEG.

TextMetrics class ​

ts
class TextMetrics

Glyph metrics for a string under the active font, returned by DrawContext.measureText.

TextMetrics.width ​

ts
readonly width: float

Advance width: total horizontal space the text occupies.

TextMetrics.height ​

ts
readonly height: float

Total vertical extent (ascent + descent).

TextMetrics.ascent ​

ts
readonly ascent: float

Distance from the baseline to the highest glyph point.

TextMetrics.descent ​

ts
readonly descent: float

Distance from the baseline to the lowest glyph point.

TextMetrics.leftBearing ​

ts
readonly leftBearing: float

Horizontal padding to the left of the first glyph's ink.

TextMetrics.rightBearing ​

ts
readonly rightBearing: float

Horizontal padding to the right of the last glyph's ink.

Bitmap class ​

ts
class Bitmap

2D pixel buffer. Owns its memory; pixel data is freed when the Bitmap is garbage-collected, or immediately when dispose() is called.

Pixels are stored row-major, top-left origin. Colors are 32-bit Color values (one packed 0xRRGGBBAA uint32) — use the Color helpers to build them.

Example

ts
import { Bitmap } from "bitmap";
const bmp: Bitmap = new Bitmap(320, 240);
bmp.fill(Color.rgb(0, 0, 0));
bmp.fillRect(10, 10, 50, 50, Color.rgb(255, 0, 0));

Bitmap.width ​

ts
readonly width: int

Width in pixels. Read-only — set at construction.

Bitmap.height ​

ts
readonly height: int

Height in pixels. Read-only — set at construction.

Bitmap.format ​

ts
readonly format: string

Pixel format identifier. One of BitmapFormat's string values.

Bitmap.channels ​

ts
readonly channels: int

Number of color channels in the active format (3 for RGB, 4 for RGBA).

Bitmap.byteSize ​

ts
readonly byteSize: int

Total size of the pixel buffer in bytes.

new Bitmap() ​

ts
constructor(width: int, height: int)
constructor(width: int, height: int, format: BitmapFormat)

Allocate a new bitmap of width x height pixels in RGBA8 format. Pixel contents are uninitialized — call fill() before reading.

Bitmap.dispose ​

ts
dispose(): void

Free the pixel buffer immediately. Any further operation on this bitmap signals an error. Idempotent — safe to call more than once.

Bitmap.getPixel ​

ts
getPixel(x: int, y: int): Color

Read the pixel at (x, y) as a packed 0xRRGGBBAA integer. Out-of-bounds coordinates return zero rather than erroring.

Bitmap.setPixel ​

ts
setPixel(x: int, y: int, color: Color): void

Write color (packed 0xRRGGBBAA) to the pixel at (x, y). Out-of-bounds coordinates are silently ignored.

Bitmap.getPixelPacked ​

ts
getPixelPacked(x: int, y: int): int

Read the pixel at (x, y) in the bitmap's native packed layout. The exact byte order depends on format; intended for fast paths that round-trip through setPixelPacked rather than mixing with Color helpers.

Bitmap.setPixelPacked ​

ts
setPixelPacked(x: int, y: int, packed: int): void

Write packed (native layout) to the pixel at (x, y). Pair with getPixelPacked for format-preserving copies.

Bitmap.fill ​

ts
fill(color: Color): void

Fill every pixel with color (packed 0xRRGGBBAA).

Bitmap.fillRect ​

ts
fillRect(x: int, y: int, w: int, h: int, color: Color): void

Fill the axis-aligned rectangle (x, y, w, h) with color.

Bitmap.drawLine ​

ts
drawLine(x0: int, y0: int, x1: int, y1: int, color: Color): void

Draw a 1-pixel line from (x0, y0) to (x1, y1) in color.

Bitmap.drawRect ​

ts
drawRect(x: int, y: int, w: int, h: int, color: Color): void

Draw the outline of the rectangle (x, y, w, h) in color.

Bitmap.drawCircle ​

ts
drawCircle(cx: int, cy: int, r: int, color: Color): void

Draw the outline of a circle centered at (cx, cy) with radius r.

Bitmap.fillCircle ​

ts
fillCircle(cx: int, cy: int, r: int, color: Color): void

Fill the circle centered at (cx, cy) with radius r.

Bitmap.composite ​

ts
composite(src: Bitmap, destX: int, destY: int, blendMode?: BlendMode): void

Composite src onto this bitmap with the top-left corner of src at (destX, destY). Defaults to BlendMode.ALPHA.

Bitmap.blit ​

ts
blit(src: Bitmap, destX: int, destY: int): void

Direct copy of src onto this bitmap with the top-left corner at (destX, destY). Faster than composite because it skips blending — pixels are overwritten.

Bitmap.drawScaled ​

ts
drawScaled(src: Bitmap, destX: int, destY: int, destW: int, destH: int, filter: ScaleFilter, blendMode?: BlendMode): void

Scale src to (destW, destH) and composite at (destX, destY). blendMode defaults to BlendMode.ALPHA.

Bitmap.blur ​

ts
blur(radius?: int): void

Box blur with the given pixel radius. Defaults to 1.

Bitmap.gaussianBlur ​

ts
gaussianBlur(sigma?: float): void

Gaussian blur with the given sigma. Defaults to 1.0.

Bitmap.sharpen ​

ts
sharpen(amount?: float): void

Unsharp-mask sharpen by amount (1.0 = neutral). Defaults to 1.0.

Bitmap.grayscale ​

ts
grayscale(): void

Convert all pixels to luma-weighted grayscale, in place.

Bitmap.invert ​

ts
invert(): void

Invert R, G, B channels, in place. Alpha is preserved.

Bitmap.sepia ​

ts
sepia(intensity?: float): void

Sepia tone, in place. intensity blends between original and full sepia (0.0 = none, 1.0 = full). Defaults to 1.0.

Bitmap.adjustBrightness ​

ts
adjustBrightness(delta: float): void

Add delta (-1.0 to 1.0) to every channel.

Bitmap.adjustContrast ​

ts
adjustContrast(factor: float): void

Multiply contrast around mid-gray by factor (1.0 = unchanged).

Bitmap.adjustHue ​

ts
adjustHue(degrees: float): void

Rotate hue by degrees (-360 to 360).

Bitmap.adjustSaturation ​

ts
adjustSaturation(factor: float): void

Multiply saturation by factor (0.0 = grayscale, 1.0 = unchanged).

Bitmap.adjustOpacity ​

ts
adjustOpacity(factor: float): void

Multiply alpha by factor (0.0 = transparent, 1.0 = unchanged).

Bitmap.pixelate ​

ts
pixelate(size?: int): void

Quantize into size-pixel blocks for a mosaic effect. Defaults to 4.

Bitmap.tint ​

ts
tint(color: Color): void

Multiply every pixel by color. Preserves alpha.

Bitmap.replaceColor ​

ts
replaceColor(from: Color, to: Color, tolerance?: int): void

Replace every pixel within tolerance of from with to. tolerance is in 0-255 distance per channel; 0 means exact match.

Bitmap.posterize ​

ts
posterize(levels?: int): void

Posterize each channel to levels discrete values. Defaults to 4.

Bitmap.threshold ​

ts
threshold(level?: float): void

Binarize: pixels with luma >= level (0.0 to 1.0) become white, others black. Defaults to 0.5.

Bitmap.applyMask ​

ts
applyMask(mask: Bitmap): void

Multiply this bitmap's alpha channel by mask's luma, pixel by pixel. mask must match this bitmap's dimensions.

Bitmap.crop ​

ts
crop(x: int, y: int, w: int, h: int): Bitmap

Return a new bitmap containing the rectangle (x, y, w, h).

Bitmap.resize ​

ts
resize(w: int, h: int, filter?: ScaleFilter): Bitmap

Return a new bitmap resized to (w, h). filter defaults to ScaleFilter.BILINEAR.

Bitmap.flipH ​

ts
flipH(): Bitmap

Return a new bitmap mirrored horizontally.

Bitmap.flipV ​

ts
flipV(): Bitmap

Return a new bitmap mirrored vertically.

Bitmap.rotate90 ​

ts
rotate90(): Bitmap

Return a new bitmap rotated 90° clockwise.

Bitmap.rotate180 ​

ts
rotate180(): Bitmap

Return a new bitmap rotated 180°.

Bitmap.rotate270 ​

ts
rotate270(): Bitmap

Return a new bitmap rotated 270° clockwise (90° counter-clockwise).

Bitmap.rotate ​

ts
rotate(degrees: float, bgColor?: Color): Bitmap

Return a new bitmap rotated by an arbitrary angle. The output is sized to fit the rotated source; new corners are filled with bgColor (default fully transparent).

Bitmap.trim ​

ts
trim(bg?: Color): Bitmap

Return a new bitmap with edges of color bg (default fully transparent) trimmed away.

Bitmap.pad ​

ts
pad(top: int, right: int, bottom: int, left: int, fill?: Color): Bitmap

Return a new bitmap padded by the given margins, filling new pixels with fill (default fully transparent).

Bitmap.convert ​

ts
convert(format: BitmapFormat): Bitmap

Return a new bitmap converted to format.

Bitmap.equals ​

ts
equals(other: Bitmap): boolean

True when other has identical dimensions, format, and pixels.

Bitmap.diff ​

ts
diff(other: Bitmap): Bitmap

Return a new bitmap whose pixels are the absolute difference between this and other, channel-by-channel.

Bitmap.clone ​

ts
clone(): Bitmap

Return an independent copy of this bitmap.

Bitmap.encode ​

ts
encode(format: ImageFormat): Buffer

Encode the bitmap to a Buffer in the given file format. Pair with Files.writeFile to save to disk.

Bitmap.context ​

ts
context(): DrawContext

Open a Canvas2D-style drawing context against this bitmap. The returned DrawContext keeps this bitmap alive for as long as it is referenced.

Bitmap.scan ​

ts
scan(fn?: Function): Array<[int, int, Color]>

Return every pixel as [x, y, color] tuples.

Bitmaps larger than 4 megapixels are rejected — use getRegion() to slice subsets first.

Parameters

  • fn: (NYI) When provided, will be called for each pixel as fn(x: int, y: int, color: Color): void and the array return becomes empty. Until the C++ wires the callback path, fn is ignored and the method behaves identically to the no-arg form. Future-proofed as optional so the callback shape can land without a breaking change.

Bitmap.pixels ​

ts
pixels(): Array<Color>

Return every pixel color as a flat Array<Color>, row-major.

Subject to the same 4-megapixel cap as scan().

Bitmap.region ​

ts
region(x: int, y: int, w: int, h: int): Array<Color>

Return the colors of the pixels inside (x, y, w, h) as a flat Array<Color>, row-major. Out-of-bounds portions are silently dropped.

Bitmap.edgeDetect ​

ts
edgeDetect(): Bitmap

Return a new bitmap containing only edge pixels (Sobel-style).

Bitmap.emboss ​

ts
emboss(angle?: float, strength?: float): void

In-place emboss effect.

angle is the light direction in degrees (default 135). strength scales the effect (default 1.0).

Bitmap.getRegion ​

ts
getRegion(x: int, y: int, w: int, h: int): Bitmap

Return a new bitmap containing the rectangle (x, y, w, h).

Bitmap.putRegion ​

ts
putRegion(src: Bitmap, x: int, y: int): void

Paste src into this bitmap with its top-left at (x, y). Direct copy, no blending.

Bitmap.contentBounds ​

ts
contentBounds(threshold?: int): BitmapRect

Return the smallest BitmapRect enclosing pixels above threshold alpha (default 0).

Bitmap.fromBuffer ​

ts
static fromBuffer(buffer: Buffer): Bitmap

Decode an image Buffer into a new Bitmap. Format is detected from the buffer header (PNG, JPEG, BMP, TGA, WebP).

Example

ts
import { Bitmap } from "bitmap";
import { Files } from "fs";
const png: any = await Files.readFile("sprite.png");
const image: Bitmap = Bitmap.fromBuffer(png);
console.log(image.width, image.height);

DrawContext class ​

ts
class DrawContext

Canvas2D-style drawing context bound to a Bitmap. Obtained via bmp.context(). State is layered: save() pushes the current style/clip/transform; restore() pops it.

Floating-point coordinates are accepted and rasterized with antialiasing when enabled (setAntialias(true), the default).

DrawContext.save ​

ts
save(): void

Push the current drawing state (style, clip, transform) onto the stack.

DrawContext.restore ​

ts
restore(): void

Pop the most recently saved drawing state.

DrawContext.reset ​

ts
reset(): void

Reset all drawing state to defaults and clear the state stack.

DrawContext.setFillColor ​

ts
setFillColor(color: Color): void

Set the fill color used by fill* methods. Packed 0xRRGGBBAA.

DrawContext.setStrokeColor ​

ts
setStrokeColor(color: Color): void

Set the stroke color used by stroke* methods. Packed 0xRRGGBBAA.

DrawContext.setLineWidth ​

ts
setLineWidth(width: float): void

Set the stroke line width in pixels.

DrawContext.setLineCap ​

ts
setLineCap(cap: LineCap): void

Set the line end style.

DrawContext.setLineJoin ​

ts
setLineJoin(join: LineJoin): void

Set the line join style.

DrawContext.setGlobalAlpha ​

ts
setGlobalAlpha(alpha: float): void

Multiply all subsequent draws by alpha (0.0 to 1.0).

DrawContext.setBlendMode ​

ts
setBlendMode(mode: BlendMode): void

Set the blend mode for subsequent draws.

DrawContext.setAntialias ​

ts
setAntialias(enabled: boolean): void

Toggle antialiasing for subsequent draws. Defaults to enabled.

DrawContext.clearRect ​

ts
clearRect(x: float, y: float, w: float, h: float): void

Clear (x, y, w, h) to fully transparent.

DrawContext.fillRect ​

ts
fillRect(x: float, y: float, w: float, h: float): void

Fill the rectangle (x, y, w, h) with the current fill color.

DrawContext.strokeRect ​

ts
strokeRect(x: float, y: float, w: float, h: float): void

Stroke the outline of the rectangle (x, y, w, h).

DrawContext.fillCircle ​

ts
fillCircle(cx: float, cy: float, r: float): void

Fill the circle centered at (cx, cy) with radius r.

DrawContext.strokeCircle ​

ts
strokeCircle(cx: float, cy: float, r: float): void

Stroke the outline of the circle centered at (cx, cy) with radius r.

DrawContext.drawLine ​

ts
drawLine(x0: float, y0: float, x1: float, y1: float): void

Stroke a line from (x0, y0) to (x1, y1).

DrawContext.fillRoundRect ​

ts
fillRoundRect(x: float, y: float, w: float, h: float, radius: float): void

Fill the rounded rectangle (x, y, w, h) with corner radius.

DrawContext.strokeRoundRect ​

ts
strokeRoundRect(x: float, y: float, w: float, h: float, radius: float): void

Stroke the rounded rectangle (x, y, w, h) with corner radius.

DrawContext.fillEllipse ​

ts
fillEllipse(cx: float, cy: float, rx: float, ry: float): void

Fill the ellipse centered at (cx, cy) with radii (rx, ry).

DrawContext.strokeEllipse ​

ts
strokeEllipse(cx: float, cy: float, rx: float, ry: float): void

Stroke the outline of the ellipse centered at (cx, cy) with radii (rx, ry).

DrawContext.setFontFromSystem ​

ts
setFontFromSystem(name: string, size: float): void

Load a font by system family name (e.g. "Helvetica", "Arial") at the given pixel size and use it for subsequent fillText / strokeText / measureText.

The font is cached per-context by name.

DrawContext.setFontFromPath ​

ts
setFontFromPath(path: string, size: float): void

Load a font from a .ttf / .otf file at path, at the given pixel size. Cached per-context by path.

DrawContext.setFontFromBuffer ​

ts
setFontFromBuffer(buffer: Buffer, size: float): void

Load a font from an in-memory Buffer at the given pixel size. The Buffer must remain valid for the lifetime of the context.

DrawContext.setTextAlign ​

ts
setTextAlign(align: TextAlign): void

Set horizontal alignment for fillText / strokeText.

DrawContext.setTextBaseline ​

ts
setTextBaseline(baseline: TextBaseline): void

Set vertical alignment.

DrawContext.fillText ​

ts
fillText(text: string, x: float, y: float): void

Fill text at (x, y) using the current font and fill color.

DrawContext.strokeText ​

ts
strokeText(text: string, x: float, y: float): void

Stroke the outline of text at (x, y) using the current font and stroke color.

DrawContext.measureText ​

ts
measureText(text: string): TextMetrics

Measure text with the current font, returning a TextMetrics.

DrawContext.beginPath ​

ts
beginPath(): void

Start a new path, discarding any pending sub-paths.

DrawContext.closePath ​

ts
closePath(): void

Close the current sub-path with a straight line to its starting point.

DrawContext.moveTo ​

ts
moveTo(x: float, y: float): void

Move the path cursor to (x, y) without drawing.

DrawContext.lineTo ​

ts
lineTo(x: float, y: float): void

Add a straight line from the current cursor to (x, y).

DrawContext.arc ​

ts
arc(cx: float, cy: float, r: float, startAngle: float, endAngle: float, ccw?: boolean): void

Add a circular arc centered at (cx, cy) of radius r, from startAngle to endAngle (radians). When ccw is true the arc is drawn counter-clockwise.

DrawContext.arcTo ​

ts
arcTo(x1: float, y1: float, x2: float, y2: float, radius: float): void

Add an arc tangent to the line from the cursor to (x1, y1) and the line from (x1, y1) to (x2, y2), with the given radius.

DrawContext.bezierTo ​

ts
bezierTo(cp1x: float, cp1y: float, cp2x: float, cp2y: float, x: float, y: float): void

Add a cubic Bézier curve to (x, y) with control points (cp1x, cp1y) and (cp2x, cp2y).

DrawContext.quadraticTo ​

ts
quadraticTo(cpx: float, cpy: float, x: float, y: float): void

Add a quadratic Bézier curve to (x, y) with control point (cpx, cpy).

DrawContext.rect ​

ts
rect(x: float, y: float, w: float, h: float): void

Add a closed rectangle sub-path.

DrawContext.fill ​

ts
fill(): void

Fill the current path with the current fill color.

DrawContext.stroke ​

ts
stroke(): void

Stroke the current path with the current stroke color and line settings.

DrawContext.clip ​

ts
clip(): void

Restrict subsequent drawing to the current path.

DrawContext.resetClip ​

ts
resetClip(): void

Remove any active clip region.

DrawContext.floodFill ​

ts
floodFill(x: int, y: int, tolerance?: float): void

Fill connected pixels reachable from (x, y) whose color matches the seed within tolerance (0.0 to 1.0, default 0).

DrawContext.isPointInPath ​

ts
isPointInPath(x: float, y: float): boolean

True when (x, y) is inside the current path's filled region.

DrawContext.isPointInStroke ​

ts
isPointInStroke(x: float, y: float): boolean

True when (x, y) is inside the current path's stroked outline.


Generated from lang/types/bitmap.d.tks in the ThicketScript repository.