Image extension
Loading and Saving
Save image files and load them again.
Connecting Image to files
save_image saves an Image to a file; load_image reads one. Supported formats such as PNG and JPEG depend on the Qt image plugins supplied with the application.
Try it first
#include <small/image.h>
void small_main()
{
Image made(200, 120, Cyan);
for (int y = 30; y < 90; y++)
for (int x = 40; x < 160; x++)
made.set_pixel(x, y, Magenta);
save_image(made, "small_image_test.png");
Image loaded = load_image("small_image_test.png");
print("Loaded: ", loaded.width(), " x ", loaded.height());
Window window;
window.open(500, 300);
while (window.is_open())
{
window.clear(Black);
draw_image(window, loaded, 150, 80);
window.show();
}
}
The filename chooses the format
An extension such as in save_image(image, "picture.png") chooses the saved format. Small reports a runtime error if a file cannot be opened or saved.
draw_image composites the loaded image's alpha information.
One step further
#include <small/image.h>
void small_main()
{
Image image(120, 80, Yellow);
save_image(image, "picture.png");
Image copy = load_image("picture.png");
print(copy.width(), " x ", copy.height());
}
The basic Image workflow is complete
You can create or load an image, inspect or edit its pixels, draw it, and save it. These operations are ordinary C++ library APIs designed for use outside Small IDE too.
Exercise — Save and read
Save a 50 × 50 Cyan image as cyan.png, then load it into a new Image.
#include <small/image.h>
void small_main()
{
Image image(50, 50, Cyan);
// Save and load.
}
Hint
Use Image loaded = load_image("cyan.png");.
show solution
#include <small/image.h>
void small_main()
{
Image image(50, 50, Cyan);
save_image(image, "cyan.png");
Image loaded = load_image("cyan.png");
print(loaded.width(), " x ", loaded.height());
}
Exercise — Edit a file
Create and save an image, load it again, change (0, 0) to Magenta, and save under a different name.
#include <small/image.h>
void small_main()
{
Image image(20, 20, White);
save_image(image, "original.png");
// Load, change one pixel, and save as changed.png.
}
Hint
Using a second filename preserves the original file.
show solution
#include <small/image.h>
void small_main()
{
Image image(20, 20, White);
save_image(image, "original.png");
Image changed = load_image("original.png");
changed.set_pixel(0, 0, Magenta);
save_image(changed, "changed.png");
}
Share your finished program
Small Steps VII — Share Your Program shows how to make a Windows package. Include any image files your program loads with Add Files, then share the whole folder as a ZIP.