Images#
Decode, change and encode PNG, JPEG, BMP and PPM images without a native library.
Build, encode, decode and resize#
Save as picture.ms. An Image is a width, a height, a color mode and one flat list of bytes, so set_pixel and pixel take (x, y) and an Rgba. new_image starts black. Image.encode returns the file bytes you write with write_file; decode_image detects the format from the bytes.
Manuscript
import (
ColorMode,
ImageFormat,
Rgba,
decode_image,
new_image
) from "@std/image/image.ms"
fn main() Void! {
var picture = new_image(4, 2, ColorMode.Rgb)?
picture.set_pixel(1, 0, Rgba(255, 0, 0, 255))
png := picture.encode(ImageFormat.Png)?
back := decode_image(png)?
small := back.resize(2, 1)?
print(f"{back.width}x{back.height} -> {small.width}x{small.height}")
red := ok_or(back.pixel(1, 0), Error("pixel is outside the image", kind: "EINVAL"))?
print(f"{red.red} {red.green} {red.blue}")
}crop,flip_horizontal,flip_vertical,rotate90,convert(between gray, RGB and RGBA) andresizereturn a new image.- Decoding untrusted files is safe: malformed data is an
EBADMSGerror, anddecode_image(bytes, max_pixels)rejects a huge image before allocating it. image.encode_jpeg(JpegOptions(...))sets JPEG quality.