SDL2::Image#

📦 std

SDL2::Image - loading and saving image files.

Core SDL2 reads and writes exactly one image format, BMP. This module adds the rest through libSDL2_image: PNG and JPEG both ways, and reading for everything else that library was built with - GIF, WEBP, TIFF, AVIF, QOI, XPM and more.

use SDL2;
use SDL2::Image;

my $tex = SDL2::Image::load_texture($ren, 'sprite.png');
$ren->copy($tex, undef, [10, 10, 64, 64]);

$ren->save_png('screenshot.png');     # the frame just drawn

Saving what you drew#

$ren->save_png($path), $ren->save_jpg($path, $quality) and $ren->save_bmp($path) write the renderer’s current target to a file. They exist because doing it by hand has two traps that produce a wrong-looking image rather than an error:

  • the bytes come back RGBA, and most image libraries want a different channel order, so they have to be swizzled;

  • a row of pixels is not always width * 4 bytes - libraries pad rows to an alignment, and the padding has to be skipped.

These methods do neither by hand: the pixels go straight into a surface that already agrees with them, and SDL2_image writes it.

What this build can do#

SDL2::Image::have_image() says whether libSDL2_image was found at all, and SDL2::Image::init($flags) asks it to load the codecs you need, returning the ones it got. A format its build lacks fails on use rather than at load.

Functions#

Loading#

load#

Reads an image file into an SDL2::Surface, guessing the format from the file’s own contents rather than its name. Croaks if the file cannot be read or its format is not one this build has.

load_texture#

Reads an image file straight into an SDL2::Texture for a renderer, which is what you want for a sprite: it skips the surface entirely.

Saving#

save_png#

Writes a surface as a PNG. Returns 0 on success.

save_jpg#

Writes a surface as a JPEG at the given quality, 0 to 100. Returns 0 on success.

Library information#

have_image#

True when libSDL2_image was found on this machine.

init#

Loads the codecs named by the OR of IMG_INIT_* flags, returning the OR of those it actually got - which may be fewer than you asked for.

quit#

Releases the codecs init loaded.