Image extension
Pixels
Read and change individual Image pixels using Pixel and set_pixel.
An image is a grid of pixels
Change a pixel's color with set_pixel(x, y, color) and read it with pixel(x, y). As in Window, (0, 0) is the top-left corner.
Try it first
Example · example1.cpp
#include <small/image.h>
void small_main()
{
Image image(256, 256, Black);
for (int y = 0; y < image.height(); y++)
for (int x = 0; x < image.width(); x++)
image.set_pixel(x, y, rgb(x, y, 180));
Window window;
window.open(520, 320);
while (window.is_open())
{
window.clear(Black);
draw_image(window, image, 32, 32);
window.show();
}
}
Creating pixels makes algorithms visible
Two nested loops visiting every pixel let you build gradients, patterns, and simple image processing yourself. Out-of-range pixel coordinates are reported as errors.
One step further
Example · example2.cpp
#include <small/image.h>
void small_main()
{
Image image(200, 200, Black);
for (int y = 0; y < image.height(); y++)
for (int x = 0; x < image.width(); x++)
if ((x / 20 + y / 20) % 2 == 0)
image.set_pixel(x, y, White);
save_image(image, "checker.png");
print("Saved checker.png");
}
Pixel work and drawing are separate
Changing data inside Image is a member operation. Displaying the result in a Window uses draw_image.
Exercise — A diagonal
Draw a Yellow diagonal from (0, 0) to (99, 99) in a 100 × 100 Black image.
Exercise starter · exercise1_starter.cpp
#include <small/image.h>
void small_main()
{
Image image(100, 100, Black);
// Draw a yellow diagonal with set_pixel.
save_image(image, "diagonal.png");
}
Hint
Use the loop's i for both x and y.
show solution
#include <small/image.h>
void small_main()
{
Image image(100, 100, Black);
for (int i = 0; i < 100; i++)
image.set_pixel(i, i, Yellow);
save_image(image, "diagonal.png");
}
Exercise — Read a pixel
Read pixel (10, 10) in a Red image and print its red component.
Exercise starter · exercise2_starter.cpp
#include <small/image.h>
void small_main()
{
Image image(30, 30, Red);
// Read and print the red component.
}
Hint
After Color color = image.pixel(10, 10);, use color.red().
show solution
#include <small/image.h>
void small_main()
{
Image image(30, 30, Red);
Color color = image.pixel(10, 10);
print(color.red());
}