UVTC's Blog

Create a Graphics Image from Pixels

2020-01-06

One simple way to draw an image by specifying the colors of pixels is to use the venerable and open Netpbm format. This is a plain text format where you specify each pixel’s color values (red, green, & blue) in order from left to right, top to bottom, and then optionally convert that resulting text file to some other format, such as png, for easy viewing.

If you don’t already have the netpbm software installed, on Debian GNU/Linux you can get it via apt install netpbm .

For example, this foo.ppm file:

converted to png via

pnmtopng foo.ppm > foo.png

yields this 10×18-pixel image:

As another example, this code (written in Haxe) generates a ppm file representing a 100 × 100 image of randomly-colored pixels:

For me, this yields:

If you instead want to color particular pixels based on their position, say, relative to the center of the box, then you need some way to figure out a given pixel’s “x” and “y” coordinates from those “i-j” values in the code above.

In the following code, after calculating x & y from i & j (assume the x-axis goes to the right, and the y-axis goes up.), I also went and computed r (distance out from the center of the box) and θ (angle from the x-axis to r), and then colored the pixels taking r and θ into account.

which results in:

Notice how: