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>. An animated GIF or WebP gives 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) starts at (y * width + x) * 4. Every file decodes to this layout, whatever it stored, 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. Decoding fails for data that is not one of these formats, for a file cut short, and for one claiming more than 100 million pixels, which is refused before any of it is decoded.
// 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
}
}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
}
}Run a program to see what it prints here.