Loft has a built-in Image type for loading PNG files and inspecting their pixels. Loading a PNG takes one function call; after that you can read every pixel, check the dimensions, and iterate over the whole image with a for loop.
Loading an Image
Pass a File handle to the 'png()' function to load a PNG into memory. The entire file is read and decoded at this point. After the call you can access pixels as many times as you like with no further I/O.
img = png(file("photo.png"))
If the file does not exist or is not a valid PNG, 'img' will be null and you can check for that with '!' before proceeding.
Checking Dimensions
Once loaded, 'img#width' and 'img#height' give you the pixel dimensions. These are read-only attributes — you cannot resize an image by writing to them.
w = img#width h = img#height println("image is {w} x {h} pixels — {w * h} pixels total")
Accessing Individual Pixels
Index the image with two integer coordinates [x, y] to get a pixel value. x = 0 is the left column; y = 0 is the top row. Each pixel carries four channels, all in the range 0–255:
px = img[x, y] r = px#red // red channel g = px#green // green channel b = px#blue // blue channel a = px#alpha // opacity (255 = fully opaque, 0 = fully transparent)
A pixel from outside the image bounds is null.
Iterating Over All Pixels
A 'for' loop over an image visits every pixel from top-left to bottom-right, row by row. This is the easiest way to scan or analyse the whole image.
bright_red = 0; for px in img { if px#red > 200 and px#green < 50 and px#blue < 50 { bright_red += 1; } } println("found {bright_red} bright-red pixels")
Practical example: average brightness
Here is how you would compute the average brightness of an image. Brightness is often approximated as (r + g + b) / 3, or the more perceptually accurate formula (0.299*r + 0.587*g + 0.114*b).
total = 0; count = 0; for px in img { total += px#red + px#green + px#blue; count += 1; } if count > 0 { avg = total / (count * 3); println("average brightness: {avg} / 255") } Note: PNG test files are not included in the standard test suite, so the examples above are shown as comments rather than runnable assertions. Paste them into your own project and point them at a real PNG file to try.
fn main() {
}