bitmap
Bitmaps: load, draw, composite and save images.
Import
ts
import { BitmapFormat, BlendMode, ScaleFilter, LineCap, ... } from "bitmap";BitmapFormat enum
ts
enum BitmapFormatPixel 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 BlendModeCompositing 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-channelmin(dest, src).BlendMode.LIGHTEN: Per-channelmax(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 ScaleFilterSampling 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 LineCapLine-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 LineJoinLine-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 TextAlignHorizontal 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 TextBaselineVertical 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 ImageFormatFile 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 TextMetricsGlyph metrics for a string under the active font, returned by DrawContext.measureText.
TextMetrics.width
ts
readonly width: floatAdvance width: total horizontal space the text occupies.
TextMetrics.height
ts
readonly height: floatTotal vertical extent (ascent + descent).
TextMetrics.ascent
ts
readonly ascent: floatDistance from the baseline to the highest glyph point.
TextMetrics.descent
ts
readonly descent: floatDistance from the baseline to the lowest glyph point.
TextMetrics.leftBearing
ts
readonly leftBearing: floatHorizontal padding to the left of the first glyph's ink.
TextMetrics.rightBearing
ts
readonly rightBearing: floatHorizontal padding to the right of the last glyph's ink.
Bitmap class
ts
class Bitmap2D 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: intWidth in pixels. Read-only — set at construction.
Bitmap.height
ts
readonly height: intHeight in pixels. Read-only — set at construction.
Bitmap.format
ts
readonly format: stringPixel format identifier. One of BitmapFormat's string values.
Bitmap.channels
ts
readonly channels: intNumber of color channels in the active format (3 for RGB, 4 for RGBA).
Bitmap.byteSize
ts
readonly byteSize: intTotal 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(): voidFree 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): ColorRead 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): voidWrite color (packed 0xRRGGBBAA) to the pixel at (x, y). Out-of-bounds coordinates are silently ignored.
Bitmap.getPixelPacked
ts
getPixelPacked(x: int, y: int): intRead 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): voidWrite packed (native layout) to the pixel at (x, y). Pair with getPixelPacked for format-preserving copies.
Bitmap.fill
ts
fill(color: Color): voidFill every pixel with color (packed 0xRRGGBBAA).
Bitmap.fillRect
ts
fillRect(x: int, y: int, w: int, h: int, color: Color): voidFill the axis-aligned rectangle (x, y, w, h) with color.
Bitmap.drawLine
ts
drawLine(x0: int, y0: int, x1: int, y1: int, color: Color): voidDraw 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): voidDraw the outline of the rectangle (x, y, w, h) in color.
Bitmap.drawCircle
ts
drawCircle(cx: int, cy: int, r: int, color: Color): voidDraw the outline of a circle centered at (cx, cy) with radius r.
Bitmap.fillCircle
ts
fillCircle(cx: int, cy: int, r: int, color: Color): voidFill the circle centered at (cx, cy) with radius r.
Bitmap.composite
ts
composite(src: Bitmap, destX: int, destY: int, blendMode?: BlendMode): voidComposite 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): voidDirect 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): voidScale src to (destW, destH) and composite at (destX, destY). blendMode defaults to BlendMode.ALPHA.
Bitmap.blur
ts
blur(radius?: int): voidBox blur with the given pixel radius. Defaults to 1.
Bitmap.gaussianBlur
ts
gaussianBlur(sigma?: float): voidGaussian blur with the given sigma. Defaults to 1.0.
Bitmap.sharpen
ts
sharpen(amount?: float): voidUnsharp-mask sharpen by amount (1.0 = neutral). Defaults to 1.0.
Bitmap.grayscale
ts
grayscale(): voidConvert all pixels to luma-weighted grayscale, in place.
Bitmap.invert
ts
invert(): voidInvert R, G, B channels, in place. Alpha is preserved.
Bitmap.sepia
ts
sepia(intensity?: float): voidSepia 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): voidAdd delta (-1.0 to 1.0) to every channel.
Bitmap.adjustContrast
ts
adjustContrast(factor: float): voidMultiply contrast around mid-gray by factor (1.0 = unchanged).
Bitmap.adjustHue
ts
adjustHue(degrees: float): voidRotate hue by degrees (-360 to 360).
Bitmap.adjustSaturation
ts
adjustSaturation(factor: float): voidMultiply saturation by factor (0.0 = grayscale, 1.0 = unchanged).
Bitmap.adjustOpacity
ts
adjustOpacity(factor: float): voidMultiply alpha by factor (0.0 = transparent, 1.0 = unchanged).
Bitmap.pixelate
ts
pixelate(size?: int): voidQuantize into size-pixel blocks for a mosaic effect. Defaults to 4.
Bitmap.tint
ts
tint(color: Color): voidMultiply every pixel by color. Preserves alpha.
Bitmap.replaceColor
ts
replaceColor(from: Color, to: Color, tolerance?: int): voidReplace 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): voidPosterize each channel to levels discrete values. Defaults to 4.
Bitmap.threshold
ts
threshold(level?: float): voidBinarize: pixels with luma >= level (0.0 to 1.0) become white, others black. Defaults to 0.5.
Bitmap.applyMask
ts
applyMask(mask: Bitmap): voidMultiply 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): BitmapReturn a new bitmap containing the rectangle (x, y, w, h).
Bitmap.resize
ts
resize(w: int, h: int, filter?: ScaleFilter): BitmapReturn a new bitmap resized to (w, h). filter defaults to ScaleFilter.BILINEAR.
Bitmap.flipH
ts
flipH(): BitmapReturn a new bitmap mirrored horizontally.
Bitmap.flipV
ts
flipV(): BitmapReturn a new bitmap mirrored vertically.
Bitmap.rotate90
ts
rotate90(): BitmapReturn a new bitmap rotated 90° clockwise.
Bitmap.rotate180
ts
rotate180(): BitmapReturn a new bitmap rotated 180°.
Bitmap.rotate270
ts
rotate270(): BitmapReturn a new bitmap rotated 270° clockwise (90° counter-clockwise).
Bitmap.rotate
ts
rotate(degrees: float, bgColor?: Color): BitmapReturn 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): BitmapReturn 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): BitmapReturn a new bitmap padded by the given margins, filling new pixels with fill (default fully transparent).
Bitmap.convert
ts
convert(format: BitmapFormat): BitmapReturn a new bitmap converted to format.
Bitmap.equals
ts
equals(other: Bitmap): booleanTrue when other has identical dimensions, format, and pixels.
Bitmap.diff
ts
diff(other: Bitmap): BitmapReturn a new bitmap whose pixels are the absolute difference between this and other, channel-by-channel.
Bitmap.clone
ts
clone(): BitmapReturn an independent copy of this bitmap.
Bitmap.encode
ts
encode(format: ImageFormat): BufferEncode the bitmap to a Buffer in the given file format. Pair with Files.writeFile to save to disk.
Bitmap.context
ts
context(): DrawContextOpen 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 asfn(x: int, y: int, color: Color): voidand the array return becomes empty. Until the C++ wires the callback path,fnis 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(): BitmapReturn a new bitmap containing only edge pixels (Sobel-style).
Bitmap.emboss
ts
emboss(angle?: float, strength?: float): voidIn-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): BitmapReturn a new bitmap containing the rectangle (x, y, w, h).
Bitmap.putRegion
ts
putRegion(src: Bitmap, x: int, y: int): voidPaste src into this bitmap with its top-left at (x, y). Direct copy, no blending.
Bitmap.contentBounds
ts
contentBounds(threshold?: int): BitmapRectReturn the smallest BitmapRect enclosing pixels above threshold alpha (default 0).
Bitmap.fromBuffer
ts
static fromBuffer(buffer: Buffer): BitmapDecode 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 DrawContextCanvas2D-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(): voidPush the current drawing state (style, clip, transform) onto the stack.
DrawContext.restore
ts
restore(): voidPop the most recently saved drawing state.
DrawContext.reset
ts
reset(): voidReset all drawing state to defaults and clear the state stack.
DrawContext.setFillColor
ts
setFillColor(color: Color): voidSet the fill color used by fill* methods. Packed 0xRRGGBBAA.
DrawContext.setStrokeColor
ts
setStrokeColor(color: Color): voidSet the stroke color used by stroke* methods. Packed 0xRRGGBBAA.
DrawContext.setLineWidth
ts
setLineWidth(width: float): voidSet the stroke line width in pixels.
DrawContext.setLineCap
ts
setLineCap(cap: LineCap): voidSet the line end style.
DrawContext.setLineJoin
ts
setLineJoin(join: LineJoin): voidSet the line join style.
DrawContext.setGlobalAlpha
ts
setGlobalAlpha(alpha: float): voidMultiply all subsequent draws by alpha (0.0 to 1.0).
DrawContext.setBlendMode
ts
setBlendMode(mode: BlendMode): voidSet the blend mode for subsequent draws.
DrawContext.setAntialias
ts
setAntialias(enabled: boolean): voidToggle antialiasing for subsequent draws. Defaults to enabled.
DrawContext.clearRect
ts
clearRect(x: float, y: float, w: float, h: float): voidClear (x, y, w, h) to fully transparent.
DrawContext.fillRect
ts
fillRect(x: float, y: float, w: float, h: float): voidFill the rectangle (x, y, w, h) with the current fill color.
DrawContext.strokeRect
ts
strokeRect(x: float, y: float, w: float, h: float): voidStroke the outline of the rectangle (x, y, w, h).
DrawContext.fillCircle
ts
fillCircle(cx: float, cy: float, r: float): voidFill the circle centered at (cx, cy) with radius r.
DrawContext.strokeCircle
ts
strokeCircle(cx: float, cy: float, r: float): voidStroke the outline of the circle centered at (cx, cy) with radius r.
DrawContext.drawLine
ts
drawLine(x0: float, y0: float, x1: float, y1: float): voidStroke a line from (x0, y0) to (x1, y1).
DrawContext.fillRoundRect
ts
fillRoundRect(x: float, y: float, w: float, h: float, radius: float): voidFill the rounded rectangle (x, y, w, h) with corner radius.
DrawContext.strokeRoundRect
ts
strokeRoundRect(x: float, y: float, w: float, h: float, radius: float): voidStroke the rounded rectangle (x, y, w, h) with corner radius.
DrawContext.fillEllipse
ts
fillEllipse(cx: float, cy: float, rx: float, ry: float): voidFill the ellipse centered at (cx, cy) with radii (rx, ry).
DrawContext.strokeEllipse
ts
strokeEllipse(cx: float, cy: float, rx: float, ry: float): voidStroke the outline of the ellipse centered at (cx, cy) with radii (rx, ry).
DrawContext.setFontFromSystem
ts
setFontFromSystem(name: string, size: float): voidLoad 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): voidLoad 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): voidLoad 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): voidSet horizontal alignment for fillText / strokeText.
DrawContext.setTextBaseline
ts
setTextBaseline(baseline: TextBaseline): voidSet vertical alignment.
DrawContext.fillText
ts
fillText(text: string, x: float, y: float): voidFill text at (x, y) using the current font and fill color.
DrawContext.strokeText
ts
strokeText(text: string, x: float, y: float): voidStroke the outline of text at (x, y) using the current font and stroke color.
DrawContext.measureText
ts
measureText(text: string): TextMetricsMeasure text with the current font, returning a TextMetrics.
DrawContext.beginPath
ts
beginPath(): voidStart a new path, discarding any pending sub-paths.
DrawContext.closePath
ts
closePath(): voidClose the current sub-path with a straight line to its starting point.
DrawContext.moveTo
ts
moveTo(x: float, y: float): voidMove the path cursor to (x, y) without drawing.
DrawContext.lineTo
ts
lineTo(x: float, y: float): voidAdd 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): voidAdd 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): voidAdd 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): voidAdd 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): voidAdd 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): voidAdd a closed rectangle sub-path.
DrawContext.fill
ts
fill(): voidFill the current path with the current fill color.
DrawContext.stroke
ts
stroke(): voidStroke the current path with the current stroke color and line settings.
DrawContext.clip
ts
clip(): voidRestrict subsequent drawing to the current path.
DrawContext.resetClip
ts
resetClip(): voidRemove any active clip region.
DrawContext.floodFill
ts
floodFill(x: int, y: int, tolerance?: float): voidFill 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): booleanTrue when (x, y) is inside the current path's filled region.
DrawContext.isPointInStroke
ts
isPointInStroke(x: float, y: float): booleanTrue when (x, y) is inside the current path's stroked outline.
Generated from lang/types/bitmap.d.tks in the ThicketScript repository.