The standard library
Slide 56 of 85
56imageThe standard library

Pictures

hive.image.decode(data) reads the bytes of a PNG, JPEG, GIF or WebP file — from hive.file.read, hive.file.asset or a response's body — into a Result<hive.image.Picture, hive.image.ImageError>. A moving GIF or WebP is its first frame.

A Picture is its width, its height and its pixels: a UInt8[dyn] of four bytes a pixel — red, green, blue and alpha, not multiplied by the alpha — row by row from the top left, so pixel (x, y) opens at (y * width + x) * 4. Whatever the file kept, that is what it reads into, and every index into it is proved in range like any other.

hive.image.scale(picture, width, height) is the same picture at exactly that size. Each new pixel is the average of the ones it covers, weighted by how opaque each is; a grown picture repeats them. Keeping the proportions is the caller's arithmetic: scale(p, 40, p.height * 40 / p.width).

An ImageError carries a message: for something that is no such file, one cut short, and one claiming more than 100 million pixels, which is refused before any of it is decoded.

A picture made in code, scaled and drawn
// A picture made here rather than read from a file: four by four, its pixels
// four bytes each — red, green, blue, alpha — going from black to white.
func gradient(): hive.image.Picture {
	mut UInt8[dyn] pixels = []
	for i := 0; i < 16; i++ {
		grey := UInt8(i * 17)
		append(pixels, grey)
		append(pixels, grey)
		append(pixels, grey)
		append(pixels, UInt8(255))
	}
	return hive.image.Picture(4, 4, pixels)
}

proc main(): void {
	picture := hive.image.scale(gradient(), 8, 4)
	shades := ["@", "%", "#", "*", "+", "=", "-", ":", "."]
	pixels := picture.pixels
	for y := 0; y < picture.height; y++ {
		mut line := ""
		for x := 0; x < picture.width; x++ {
			red := (y * picture.width + x) * 4
			if pixels bounds red {
				shade := Int(pixels[red]) * len(shades) / 256
				if shades bounds shade {
					line += shades[shade]
				}
			}
		}
		echo line
	}
}
A picture the program carries
proc main(): void {
	stored := hive.file.asset("logo.png")
	if stored is Result.Ok(data) {
		if hive.image.decode(data) is Result.Ok(logo) {
			echo "{logo.width} by {logo.height}"
		}
	} else if stored is Result.Error(why) {
		echo why.message
	}
}