← 输入框|imagescript.dev|刷新
ImageScript v4.1.0
    Preparing search index...

    ClassImage

    An RGBA image; provides the codecs and the manipulation functions. Methods that change the image modify it in place and return it, so calls can be chained

    Subclassing is not supported: the methods that make an image (Image.clone, Image.extract, Image.decode, ...) return plain Images, without calling a subclass' constructor.

    The maxPixels limits guard what comes from outside: decoding and rendering. new Image(), resize() and scale() make the size they are asked for, so check sizes that come from users before you pass them on

    Index
    • Creates a new image with the given dimensions, all pixels transparent black

      Parameters

      • width: number

        The width in pixels (a fraction is truncated)

      • height: number

        The height in pixels (a fraction is truncated)

      Returns Image

      TypeError if the width or height is not a number

      RangeError if the width or height is less than 1, or the image is too large to allocate

    • get bitmap(): Uint8ClampedArray

      The image's RGBA pixel data (red, green, blue and transparency, four bytes per pixel). It can be replaced by any 8-bit array with width * height * 4 bytes starting at a byte offset divisible by 4 (it is used as is, without copying). Direct changes to this array or Image.setPixelAt don't update the image's gain map.

      Returns Uint8ClampedArray

    • set bitmap(
          bitmap: Uint8Array<ArrayBufferLike> | Uint8ClampedArray<ArrayBufferLike>,
      ): void

      Replaces the pixel data

      Parameters

      • bitmap: Uint8Array<ArrayBufferLike> | Uint8ClampedArray<ArrayBufferLike>

        The new RGBA data, width * height * 4 bytes (used as is, without copying, so its byte offset has to be divisible by 4: the image reads it as 32-bit pixels too)

      Returns void

    • get gainMap(): GainMap | null

      Extra image data that lets high-dynamic-range (HDR) screens show brighter highlights. Standard screens show the image without the extra brightness. Image.encodeJPEG, Image.encodeAVIF and Image.encodeJXL can write it. null means there is no gain map. This is the image's own map, not a copy: changing it (image.gainMap.max = 3) changes the image's

      Returns GainMap | null

    • set gainMap(gainMap: GainMap | null): void

      Replaces the gain map

      Parameters

      • gainMap: GainMap | null

        The new gain map, or null to remove it

      Returns void

      The image uses a copy of the map: changing the image (resizing it, say) changes its own map only, also when the same map was given to other images, and later changes to the map you gave don't reach the image

      TypeError if it isn't a GainMap or null

    • Gets the average color of the image, weighting each pixel by its opacity

      Returns number

      The average color (fully opaque), black for fully transparent images

      Image.dominantColor for the color that most of the image has

    • Scales the blue channel

      Parameters

      • factor: number

        The factor to multiply the channel with (>= 0, results are clamped)

      Returns this

    • Blurs the image with a gaussian blur (transparent pixels don't bleed their color)

      Parameters

      • radius: number

        The blur radius: the gaussian's standard deviation in pixels, like CSS' blur()

      Returns this

    • Multiplies the color channels, e.g. 1.2 makes the image 20% brighter

      Parameters

      • factor: number

        The factor (>= 0, 1 keeps the image)

      Returns this

    • Mixes the colors of every pixel with a color matrix, like SVG's feColorMatrix: the new red, green, blue and alpha are each a sum of the old red, green, blue and alpha times a factor, plus an offset. Grayscale, sepia, tints, swapped channels, color blindness simulation or a mix of those in one pass

      Parameters

      • matrix: ArrayLike<number>

        The 9 or 20 values

      Returns this

      The values are 20 numbers, four rows of [red, green, blue, alpha, offset] for the new red, green, blue and alpha, with the colors and the offsets as 0 to 1 (like CSS and SVG): [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0] changes nothing, [0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0] swaps red and blue. Nine numbers are the first three rows without the alpha and the offsets (the alpha stays as it is). The colors are the sRGB values, not premultiplied, and the results are clamped. With a gain map (an HDR image), the HDR highlights follow the change as they do for other color changes

      image.colorMatrix([0.393, 0.769, 0.189,  0.349, 0.686, 0.168,  0.272, 0.534, 0.131]); // sepia
      
    • Makes a color transparent, like GIMP's "Color to Alpha": the color is removed from every pixel and replaced by transparency, so pixels that are partly the color (e.g. antialiased edges against a background) become semi-transparent instead of keeping a fringe of it. The color is removed everywhere in the image, not only from a connected background: removing a white background also makes white areas inside the subject (e.g. eyes in a logo) transparent

      Parameters

      Returns this

    • Composites (overlays) the source onto this image

      Parameters

      Returns this

      image.composite(overlay, { x: 10, y: 10, opacity: 0.5, mode: 'multiply' });
      

      TypeError if the source isn't an Image

    • Scales the color channels' distance from mid gray, e.g. 1.5 increases the contrast, 0.5 reduces it

      Parameters

      • factor: number

        The factor (>= 0, 1 keeps the image, 0 makes it gray)

      Returns this

    • Crops an image to the specified dimensions. The region is clipped to the image, so the result can be smaller than the requested size

      Parameters

      • x: number

        The x offset (0-based)

      • y: number

        The y offset (0-based)

      • width: number

        The new width

      • height: number

        The new height

      Returns this

    • Decodes an image (PNG, JPEG, TIFF, WebP, BMP, ICO, CUR, QOI, PBM, PGM, PPM, PAM, PFM, Radiance HDR, TGA, AVIF or JPEG XL)

      Parameters

      • input: BinaryData

        The binary data to decode

      • options: DecodeOptions = {}

        See DecodeOptions. JPEGs, TIFFs, PNGs, WebPs and JPEG XLs are rotated/mirrored as their orientation (Exif, for PNGs also XMP) says by default: photos taken with a rotated camera are stored sideways

      Returns Promise<Image>

      The decoded image

      For animations (GIFs, animated WebPs, AVIF image sequences, JPEG XL animations) this is the first frame, composed onto the canvas as Animation.decode has it, and decoding stops after it: use Animation.decode for all frames. For APNGs this is the default image, which is what viewers without APNG support show; for icons and cursors it's their largest image

      const image = await Image.decode(bytes); // the file's bytes, e.g. from fs.readFile() or fetch()
      const webp = await image.resize({ width: 800 }).encodeWebP({ quality: 80 });

      LimitError if the image has more than options.maxPixels pixels (checked before its pixels are allocated)

      Error if the data isn't a supported image, or is damaged or truncated (the underlying error is its cause)

    • Gets the image's dominant color: the colors are counted in a histogram of 16 levels per channel, and the average of the pixels in the fullest bin is returned (so it is a color the image has, not a mix of two hues)

      Parameters

      Returns number

      The image's dominant color (fully opaque); mostly transparent pixels are ignored. If every pixel is ignored as black or white, the filter is dropped

      Image.averageColor for the mix of all colors

    • Adds a shadow behind the image, shaped by its alpha: a drop shadow with an offset, or a glow without one (image.dropShadow({ blur: 8, color: 0xff2fb9ff }), with spread to make it stronger). The image grows to fit the shadow, unless expand is false

      Parameters

      Returns this

      LimitError if the size or offset of the shadow would make the image larger than an image can be

    • Encodes the image as AVIF (AV1, with an alpha image if the image has transparency)

      Parameters

      Returns Promise<Uint8Array<ArrayBuffer>>

      RangeError if the image is wider or higher than 65536 pixels

    • Encodes the image as BMP: with a palette if it is opaque and has at most 256 colors, else with 24 bit pixels, or 32 bit ones if it has transparency

      Returns Promise<Uint8Array<ArrayBuffer>>

    • Encodes the image as a GIF (one frame): at most 256 colors, transparency only on or off (pixels with an alpha below 128 become transparent). For animations, see Animation.encodeGIF

      Parameters

      Returns Promise<Uint8Array<ArrayBuffer>>

      RangeError if the image is wider or higher than 65535 pixels

    • Encodes the image into a JPEG. JPEG has no transparency: an image with transparent or translucent pixels is composited onto the background color (black by default) first, the image itself stays unchanged. An image whose pixels are all gray is written as a grayscale JPEG (one component)

      Parameters

      Returns Promise<Uint8Array<ArrayBuffer>>

      RangeError if the image is wider or higher than 65535 pixels, or the comment or the Exif fields of the metadata are longer than 65533 bytes

    • Encodes the image as JPEG XL: losslessly (the default), or lossy with a quality. Alpha (if the image has transparency) is lossless either way. The codestream is in the container, with the metadata as Exif

      Parameters

      Returns Promise<Uint8Array<ArrayBuffer>>

      Lossless works like libjxl's cjxl -e 3 (a palette of up to 1024 colors, else palettes of channels using few of their values; YCoCg; the weighted predictor in contexts of its error; grayscale if the image is), at effort 0 the codestream byte for byte like cjxl -e 1 on CPUs with AVX2 or NEON (its fast lossless mode: the gradient predictor, a palette if the image has at most 511 colors besides black, else YCoCg). Lossy works like cjxl -q: XYB, varblocks of libjxl's search, chroma from luma, the edge preserving filter

    • Encodes the image into a PNG, with the smallest lossless color type (a palette for up to 256 colors, grayscale or RGB, alpha only if needed). Uses the runtime's native zlib when available, so the compressed bytes can differ between runtimes and browsers; the pixels are the same

      Parameters

      Returns Promise<Uint8Array<ArrayBuffer>>

      The encoded data

    • Encodes the image as the smallest fitting Netpbm format: PBM for black and white images, PGM for grayscale ones, PPM for others, PAM if the image has transparency

      Returns Promise<Uint8Array<ArrayBuffer>>

    • Encodes the image as QOI (3 channels if the image is opaque)

      Returns Promise<Uint8Array<ArrayBuffer>>

    • Encodes the image as run length encoded TGA (32 bit, or 24 bit if the image is opaque)

      Parameters

      Returns Promise<Uint8Array<ArrayBuffer>>

      RangeError if the image is wider or higher than 65535 pixels

    • Encodes the image as WebP: lossless (usually 20-30% smaller than PNG, but slower to encode), or lossy with a quality below 100

      Parameters

      Returns Promise<Uint8Array<ArrayBuffer>>

      RangeError if the image is wider or higher than 16383 pixels (lossy) or 16384 (lossless): the limits of the two codecs

    • Copies a region of the image into a new image and leaves the image unchanged (like Image.crop on a clone, without copying the whole image). The region is clipped to the image, so the result can be smaller than the requested size

      Parameters

      • x: number

        The x offset (0-based)

      • y: number

        The y offset (0-based)

      • width: number

        The region's width

      • height: number

        The region's height

      Returns Image

    • Fills the image data with the supplied color. The image's gain map, if it has one, is made neutral (no boost anywhere): the new pixels have no HDR light beyond their own

      Parameters

      • color: number | ColorFunction

        The color, or a function returning the color of each pixel (checked like any color: a result that isn't a number throws a TypeError, a number that isn't a color a RangeError)

      Returns this

    • Applies a gamma correction, values above 1 brighten the dark tones, values below 1 darken them

      Parameters

      • gamma: number

        The gamma (> 0, 1 keeps the image)

      Returns this

    • Gets the pixel color at the specified position (0-based). Colors.toRGBA splits it into its channels

      Parameters

      • x: number

        The x coordinate (a fraction is dropped: 1.9 is the pixel 1)

      • y: number

        The y coordinate (likewise)

      Returns number

      The color value (0xRRGGBBAA)

      RangeError if the position isn't inside the image

      Image.pixels to go over every pixel

    • Converts the image to grayscale by its luma (ITU-R 601, like Pillow), keeping the alpha

      Returns this

    • Scales the green channel

      Parameters

      • factor: number

        The factor to multiply the channel with (>= 0, results are clamped)

      Returns this

    • Shifts the image's hue

      Parameters

      • degrees: number

        How many degrees to shift the hue by

      Returns this

    • Inverts the image's lightness (HSL), keeping hue and saturation: dark colors become light and vice versa

      Returns this

    • Inverts the image's value (HSV), keeping hue and saturation: the brightest channel v becomes 255 - v and the others scale along, black becomes white

      Returns this

    • Scales the lightness of the image (HSL), keeping its hue and saturation

      Parameters

      • factor: number

        The factor to multiply the lightness with (>= 0, results are clamped)

      Returns this

    • Scales the opacity of the image

      Parameters

      • factor: number

        The factor to multiply the opacity with (0..1 lowers it, >1 raises it, results are clamped)

      Returns this

    • Draws an outline around the image's shape (its alpha): the sticker effect for cut-out images, or an outline for text. The image grows to fit it, unless expand is false

      Parameters

      Returns this

      LimitError if the width would make the image larger than an image can be

    • Yields an [x, y, color] array for every pixel in the image (0-based), row by row. Resizing the image meanwhile doesn't affect the iteration (it goes on over the pixels the image had when pixels() was called), but other changes to the pixels, like setPixelAt(), are seen by the pixels not yet yielded

      Returns Generator<[x: number, y: number, color: number], void, undefined>

      The coordinates and color of the pixel ([x, y, color])

    • Reduces the image to a palette of at most 256 colors (or a fixed one), in place, optionally dithered

      Parameters

      Returns this

      Transparent pixels (alpha 0) keep their color and don't count towards the palette; the other pixels keep their alpha and only their RGB is reduced. The result is deterministic. With a gain map (an HDR image), the HDR highlights are dropped, like Image.invert does: the map is neutral afterwards

      image.quantize({ colors: 16, dither: 'floyd-steinberg' });
      image.quantize({ palette: [0x0f380fff, 0x306230ff, 0x8bac0fff, 0x9bbc0fff] }); // a Game Boy look
    • Sets the RGB of every pixel to the given color, keeping each pixel's own alpha. Turns an image into a silhouette or tints it: image.recolor(0xffffffff) makes every pixel white, keeping its transparency

      Parameters

      • color: number

        The color to use, its alpha is ignored

      Returns this

    • Sets the RGB of every pixel to the RGB of the same pixel of another image, keeping each pixel's own alpha. With a gradient this fills a shape with it, e.g. gradient text: text.recolor(Image.linearGradient(text.width, text.height, { stops: [0x22d3eeff, 0xfb923cff], angle: 90 }))

      Parameters

      • colors: Image

        The image to take the colors from, it has to have the same size. Its alpha is ignored

      Returns this

    • Scales the red channel

      Parameters

      • factor: number

        The factor to multiply the channel with (>= 0, results are clamped)

      Returns this

    • Creates a new image from the given SVG

      Parameters

      Returns Promise<Image>

      The rendered SVG graphic

      Supports shapes, paths, transforms, use/symbol, CSS styles, gradients, patterns, strokes, markers, clip paths, masks, opacity, blend modes, filters (all primitives and the filter functions) and images embedded as data URIs (PNG, JPEG, GIF, WebP, SVG) or given with SVGResourceOptions.images, and text with the given or embedded fonts (see SVGResourceOptions.font). Hrefs are resolved from the options and the data URIs only, never from files or URLs: drawing an image that isn't given, or can't be decoded, throws. SVGs from untrusted sources are fine to render: the size of the output, the layers and the images are limited by the options, and so is the work nested masks, clip paths, patterns, markers and filter images can multiply

      const logo = await Image.renderSVG(
      '<svg xmlns="http://www.w3.org/2000/svg" width="64" height="64"><image href="logo.png" width="64" height="64"/></svg>',
      { images: { 'logo.png': logoPNG } } // (the PNG's bytes, e.g. from a fetch or a file you read)
      );

      LimitError if the output, the layers or the images exceed the limits of the options, or the SVG exceeds a fixed limit of the work it may take: more than 100000 elements drawn through <use> references and markers, more than 10000 markers, masks, clip paths, patterns, markers and filter images nested so deeply that they would multiply, entities that expand past the size limit, or filters past their budget

      RangeError if the requested size is below 1 pixel (or a scale isn't above 0)

      Error if the SVG can't be parsed (it has no <svg> element) or an image in it can't be drawn (it isn't given or can't be decoded)

    • Creates a new image containing the rendered text

      Parameters

      • text: string

        Text to render

      • options: RenderTextOptions

        The font and size, color, layout and style, see RenderTextOptions. Without a width or height, the image grows by the outline width on every side; with one, it has exactly that size

      Returns Promise<Image>

      The rendered text

      const label = await Image.renderText('Hello, world', { font: fontBytes, size: 48, color: 0xffffffff });
      

      TypeError if the text isn't a string, or the options aren't an object with a font

      Error if the font can't be read

      LimitError if the image would have more than options.maxPixels pixels (checked before anything is allocated)

    • Resizes the image to the given dimensions. Pass ResizeToOptions with only a width or a height to keep the aspect ratio.

      Parameters

      Returns this

      The resized image

    • Resizes the image: to the given width or height (the other side keeps the aspect ratio), or to both

      Parameters

      Returns this

      The resized image

      image.resize({ width: 300, height: 200, fit: 'cover' }); // fills 300x200, cropping what doesn't fit
      image.resize({ width: 150 }); // 150 wide, the height keeps the aspect ratio
    • Rotates the image clockwise by the given angle in degrees (like CSS' rotate(); negative angles turn it counterclockwise). Multiples of 90° move whole pixels; other angles resample the image (see RotateOptions.mode). By default the image grows so the corners fit (a quarter turn swaps width and height); with expand: false it keeps its size, also for quarter turns, and what doesn't fit is cut off

      Parameters

      Returns this

      image.rotate(90);                          // a quarter turn clockwise: width and height swap
      image.rotate(-15, { expand: false }); // 15° counterclockwise, the size stays and the corners are cut off

      Image.transform for skews, flips and shifts

    • Scales the saturation of the image (HSL), keeping its hue and lightness. 0 makes it grayscale

      Parameters

      • factor: number

        The factor to multiply the saturation with (>= 0, results are clamped)

      Returns this

    • Resizes the image by the given factor: a side of 7 pixels scaled by 0.5 is 3 (fractions are dropped, a side doesn't go below 1 pixel)

      Parameters

      Returns this

    • Sets the pixel color for the specified position (0-based)

      Parameters

      • x: number

        The x coordinate

      • y: number

        The y coordinate

      • color: number

        The new color (0xRRGGBBAA)

      Returns this

      RangeError if the position isn't inside the image

    • A short description for debugging, e.g. Image<64x64>

      Returns string

    • Moves every point of the image with an affine transform, in one resampling: rotation, scaling, skew, flips and shifts in any mix and around any point

      Parameters

      Returns this

      The six numbers are SVG's matrix(a b c d e f): a point (x, y) of the image ends up at (a x + c y + e, b x + d y + f), with y pointing down. The image grows to hold the result (expand: false keeps its size), so a shift only shows with expand: false. The edges fade, like the pixels outside were transparent. A transform that flattens the image (a factor of 0) is refused. With a gain map (an HDR image), the map moves with the image

      image.transform([1, 0, Math.tan(-0.3), 1, 0, 0]);             // slanted like italics, around the middle
      image.transform([0.5, 0, 0, 0.5, 0, 0], { origin: { x: 0, y: 0 } }); // half the size
      image.transform([-1, 0, 0, 1, 0, 0]); // flipped horizontally
      const a = Math.PI / 6;
      image.transform([Math.cos(a), Math.sin(a), -Math.sin(a), Math.cos(a), 0, 0]); // turned 30° clockwise

      Image.rotate for turning by an angle

    • Removes borders of one color, e.g. the empty space around rendered text or around a logo on a solid background. An image that only has the color stays unchanged (Frame.trim also moves the frame's offsets)

      Parameters

      Returns this