NAME

Image::Pixels - the pixels of a PNG, JPEG, GIF, BMP or WebP file

VERSION

Version 0.01

SYNOPSIS

use Image::Pixels qw(decode decode_file info encode encode_file);

my $picture = decode_file('photo.jpg')
    or die "photo.jpg is not a picture that is drawn here\n";
printf "%s, %d by %d\n", @{$picture}{qw(format width height)};

my ($red, $green, $blue, $solid) = unpack 'C4', $picture->{rgba};

my $small = decode($bytes, most => 4_000_000);

my $about = info($bytes);
print "$about->{format}, $about->{width} by $about->{height}\n" if $about;

my $png = encode($picture, format => 'png');
encode_file('copy.png', $picture);
encode_file('smaller.jpg', $picture, quality => 70);

DESCRIPTION

Image::Pixels turns the bytes of a picture's file into its pixels: four bytes a pixel, a row at a time from the top, whatever kind of file they came from. It reads a PNG, a JPEG, a GIF, a BMP and a WebP, and it needs no other library installed to do it.

It is for a program that has to look at a picture, or to draw one, and that does not want to care which kind of file it was handed. It turns pixels back into a file as well: a PNG, a BMP or a WebP, each of which keeps every pixel as it was, a JPEG, which keeps a picture that looks the same in far fewer bytes, or a GIF, which keeps a picture of 256 colours or fewer and cuts the colours of any other to 256. It currently makes no picture larger or smaller and turns none round.

Every byte is read as a stranger's. A file that was cut short, or that says one thing of itself and holds another, is refused and never guessed at, and nothing is looked at past the end of what was given.

What can be imported is in "EXPORTS". An extension written in C can ask for all of it with no Perl call in between: see "CALLING FROM C".

FUNCTIONS

decode

my $picture = decode($bytes);
my $picture = decode($bytes, most => 4_000_000);

The pixels of a picture, from the bytes of its file. The answer is a hash with four things in it.

format

Which kind of file the bytes were: png, jpeg, gif, bmp or webp.

width
height

The size of the picture in pixels, as the file stores it.

rgba

The pixels, as one string of width * height * 4 bytes: four bytes a pixel, a row at a time from the top. "WHAT A PIXEL IS" says what the four are.

most is the most pixels the caller is willing to hold, and a picture of more is refused before any room is made for it. It is the caller's guard against a small file that claims a vast picture, and when it is left out the most is 256 MiB of pixels. That is 67,108,864 of them, and giving undef is the same as leaving it out. The header of a file can claim any size it likes, so give a number that suits the program whenever the bytes come from somebody else. "HOW MUCH MEMORY" says what a picture takes while it is read.

undef means that the bytes are not a picture that is drawn here, which is the ordinary answer for a file from a stranger. It is the answer for bytes that are no picture at all, for a picture that was cut short or damaged, and for a picture of one of the sorts that "WHAT IS DRAWN" lists as left out. Nothing is said of which, since for a caller they come to the same thing. "ERRORS" lists what croaks.

decode_file

my $picture = decode_file($path);
my $picture = decode_file($path, most => 4_000_000);

The same, for a file. It is read whole and then drawn.

$path is the bytes that name the file to the system, so a name with letters outside ASCII is encoded by the caller first. Only a plain file is read. A directory, a device and a pipe are refused in words, since the first has no bytes and the others may have no end.

info

my $about = info($bytes);

What a picture's file says of itself, with none of the picture drawn. It is quick, it makes no room for pixels, and it is the way to learn how large a picture is before deciding whether to hold it. The answer is a hash with four things in it.

format
width
height

As "decode" gives them.

turned

How the picture is meant to be shown, as a number from 1 to 8, when it is a JPEG that says so in its Exif block. Otherwise 0. The pixels "decode" gives are never turned, and this is how to turn them: 1 is as they are, 3 is upside down, 6 is a quarter turn clockwise and 8 a quarter turn the other way. 2, 4, 5 and 7 are those four as seen in a mirror.

The answer is undef when no size can be read: the bytes are not one of the five kinds, or they stop before the size, or the size they give is nothing by something or is more than 16,777,216 on a side.

Only the beginning is looked at. For every kind but a JPEG the size is in the first 32 bytes. A JPEG keeps it behind whatever was written before the picture itself, which can be a great deal, so give info the whole of a JPEG when the first part of it is answered with undef.

info looks at far less than "decode" does, and so it will answer for a file that "decode" refuses: one that goes wrong further in, and one of a sort that is not drawn, such as a JPEG of 12 bits. Whenever both answer, they give the same format, width and height.

Once in a while it is the other way round, and only for a JPEG that is damaged in one way. Stray bytes between two of its segments are stepped over by "decode", as the common JPEG library steps over them, and they stop info. So undef from info says that no size was read. It does not say that "decode" would draw nothing.

encode

my $bytes = encode($picture, format => 'png');

The bytes of a file, from a picture. $picture is a hash with width, height and rgba in it, as "decode" gives one. Nothing else in it is looked at, its format among it: the kind of file to write is always said, with format. All five kinds are written: png, bmp, jpeg, gif and webp.

A PNG keeps every pixel exactly as it was handed in, and the colour of a pixel that is wholly clear with it, so a picture read back from one is the picture that was written. It is written in whichever form of a PNG takes the fewest bits for each pixel: grey, a palette of up to 256 colours, or colour, each with or without how solid a pixel is.

A BMP keeps every pixel exactly as well, and packs nothing, so its file is the larger of the two: three bytes a pixel when every pixel is solid, and four when one is not. In the second of those the file says where in a pixel its red, its green, its blue and how solid it is are kept. A reader has to know of that to show a picture that is partly clear, and one that does not shows it as wholly solid. So a picture that is partly clear is safer in a PNG.

A JPEG does not keep every pixel. It keeps a picture that looks the same, in far fewer bytes, and it is the kind for a photograph. It has three settings, which no other kind has:

quality

A whole number from 1 to 100, and 85 when none is given. At 100 a picture comes back within a few parts in 255 of what it was. At 1 it is hardly the picture.

colour

half or full, and half when it is not given. Colour is then kept at half size both ways, as most JPEGs keep it, which the eye seldom sees in a photograph and which takes far fewer bytes. full keeps it whole. Ask for full where the colour changes from one pixel to the next, as it does in a drawing or in small coloured letters: at half size such colour is lost, whatever the quality.

over

A list of three whole numbers from 0 to 255: red, green and blue. A JPEG has no pixel that is partly clear, so a pixel that is not solid is laid on this colour first, and on white when none is given. It is looked at only where a pixel is not solid.

A picture that is grey in every pixel, once it is laid on its colour, is written with no colour at all, which is smaller again. A JPEG written here is byte for byte the one the common JPEG library writes for the same pixels at the same quality, with its whole-number transform.

A GIF holds 256 colours, and a pixel in one is either there or it is not. So a pixel that is less than half solid is written clear and loses its colour, and every other pixel is written solid. A picture of 256 colours or fewer, clear counted as one of them, is otherwise kept exactly. A picture of more has them cut to 256 by median cut, in which a colour counts for as much as the pixels that have it, and each pixel is then given the nearest of the 256. Nothing is dithered, so flat colour stays flat and a smooth slope of colour comes back in bands. A GIF takes no setting, and the one written here holds one picture, which does not move.

A WebP has two forms, and the one written here is the one that keeps every pixel exactly as it was handed in, the colour of a pixel that is wholly clear with it, as a PNG does. A picture read back from one is the picture that was written. Its file is usually shorter than a PNG of the same picture, though not for every picture. A picture of more than 16 colours is packed in two ways or in three, and the shortest file is the one given, so a WebP takes longer to write than a PNG. It takes no setting. The other form of a WebP, which keeps a picture that only looks the same, as a JPEG does, is read here and is not written.

Nothing goes into the file but the pixels: no date, no name of a program and no comment. So the same picture is the same bytes every time and on every machine, for one version of this module. A later version may pack the same picture into other bytes, which read back as the same pixels.

A side of a PNG is no longer than 2,147,483,647 pixels. The file of a BMP is shorter than 4 GiB, which is as much as a BMP can say of its own length. A side of a JPEG is no longer than 65,535. Nor is a side of a GIF, and there are readers that open no GIF with a side over 32,767. A side of a WebP is no longer than 16,384, and there are readers that open no WebP with a side over 16,383.

encode_file

encode_file($path, $picture);
encode_file($path, $picture, format => 'png');

The same, written to a file. It answers nothing.

Without format the kind is the one the ending of the path names: .png, .jpg, .jpeg, .gif, .bmp or .webp, in letters of either size. A path with some other ending, or none, needs format, and where both are there it is format that counts.

The picture is packed whole before anything is made on the disk. It is then written to a new file beside $path, and that file is renamed to $path once all of it is there. So there is never half a picture under the name. A file that was already there is replaced all at once, and when anything stops the writing the new file is removed and what was at $path is as it was. Where $path is a link to a file somewhere else, it is the link that is replaced and not the file it points at.

$path is bytes, as it is for "decode_file".

EXPORTS

Nothing is exported unless it is asked for.

use Image::Pixels qw(decode_file encode_file);
use Image::Pixels qw(:all);

:all is the five: decode, decode_file, info, encode and encode_file.

Each can also be called by its full name, as Image::Pixels::decode, with nothing imported.

The importing is done by Ex::Op, which takes what Exporter takes: a tag, a name left out with !, a pattern, a version.

WHAT A PIXEL IS

A pixel is four bytes: how red it is, how green, how blue, and how solid, from 255 for wholly there to 0 for not there at all. Rows come from the top down, and each row from the left. So the pixel that is $x across and $y down, both counted from 0, is

my ($red, $green, $blue, $solid)
    = unpack 'C4', substr $picture->{rgba}, 4 * ($y * $picture->{width} + $x), 4;

The colour is the colour the file stores. It has not been multiplied by how solid the pixel is, and nothing is done with what a file says of gamma or of a colour profile: no colour is changed to suit a screen.

The pixels are the picture as the file stores it, and they are never turned. A photograph that was taken with the camera on its side is stored on its side, with a note of how it is to be shown. "info" gives that note as turned, and turning the pixels is the caller's to do.

A picture handed to "encode" is the same thing: its width, its height, and in rgba four bytes for each pixel in that order.

WHAT IS DRAWN

Five kinds of file are read, and this is what is drawn of each. A picture of a sort that is left out is answered with undef, and so is a file of any other kind.

PNG

Every colour type and depth, with or without a palette, interlaced or not, and with whatever it says is see-through. A sample of 16 bits is shown by its upper 8.

JPEG

The baseline kind, the extended kind and the progressive kind, at 8 bits a sample, in grey, in colour and in four inks. A JPEG that is lossless, or arithmetic coded, or of 12 bits, is left out. What is drawn is what the common JPEG library draws when it is asked not to smooth: colour that was stored at half size is doubled by repeating it.

GIF

The first picture in the file, laid on the screen the file says it has. A GIF that moves is drawn as it first appears. The colour the file calls see-through is clear, and so is whatever the first picture does not cover.

BMP

Every header there has been, at 1, 4, 8, 16, 24 and 32 bits a pixel, with a palette, with bit fields and with either run length coding. A BMP with a JPEG or a PNG inside it is left out.

WebP

Lossy and lossless, with how solid each pixel is where the file says. Of a WebP that moves, the first frame, placed where it is shown.

HOW MUCH MEMORY

A picture that has been read is a string of four bytes for each pixel, which is 61 MiB for sixteen million pixels.

While it is being read it takes more than its string does. The pixels are held twice for a moment, which is eight bytes for each pixel, and a PNG or a JPEG takes about thirteen, with what its rows are unpacked into. So a picture of sixteen million pixels takes from 120 to 200 MiB while it is read.

How much that is depends on the size the file claims and not on how long the file is, and a file of a few hundred bytes can claim thousands of millions of pixels. most is what stands between such a file and the memory it asks for. With most left out a picture may have 67,108,864 pixels, and one of that many takes from 510 to 850 MiB while it is read. "info" gives the size a file claims and makes no room at all.

A picture that is written takes memory beside the pixels that were handed in. For a photograph that is about one byte for each pixel as a JPEG, seven as a BMP, twelve as a PNG, and from thirty to thirty-five as a GIF or as a WebP: for sixteen million pixels, from 20 MiB for a JPEG to 510 MiB for a GIF.

WHAT IS LEFT IN MEMORY

"decode_file" overwrites its own copy of the file's bytes before it returns, and both it and "decode" overwrite their own copy of the pixels. No more is promised than that. The string in rgba belongs to the caller, and its memory goes back as the memory of any string does. Not everything that was worked out on the way to the pixels is overwritten either.

"encode" and "encode_file" overwrite their own copy of the file's bytes and everything they worked those out in. The bytes that "encode" answers with belong to the caller, as the picture that was handed in does.

ERRORS

Bytes that are not a picture drawn here are answered with undef and are nobody's mistake. Everything else that stops a function is said in words, with croak:

more pixels than were allowed, or no memory for them

The picture has more pixels than most, or there was no room to draw it.

cannot read PATH: REASON

"decode_file" could not open or read the file, or it is not a plain file. REASON is the system's own.

cannot read a path with a zero byte in it
Wide character in subroutine entry

The bytes of a file, or a path, held a character above 255. Both are bytes.

a reference is not bytes

A reference was given where bytes or a path were wanted. An object that turns itself into a string is asked to, once, and that string is used.

decode: most is a whole number from 0 to 9007199254740992

most is read as a whole number and nothing else: no fraction, no word, no reference and nothing under zero.

decode does not know 'NAME'
decode takes name and value pairs

most is the only name there is.

encode needs format

Nothing else tells "encode" which kind of file to write.

encode_file: PATH does not end as a picture's file does, and no format was given
encode does not know the format 'NAME'

The kinds are png, jpeg, gif, bmp and webp. jpg is the ending of a path and is not the name of a kind.

encode: a KIND has no use for NAME

quality, colour and over are a JPEG's. A PNG takes no setting, and nor does a BMP, a GIF or a WebP.

encode: quality is a whole number from 1 to 100
encode: colour is half or full
encode: over is three whole numbers from 0 to 255: red, green and blue
encode: a picture is a hash of width, height and rgba
encode needs NAME

One of width, height and rgba is not in the picture, or is undef.

encode: width is a whole number from 1 to 4294967295

And so is height.

encode: rgba is N bytes, which is not four for each of W by H pixels
encode: a picture of W by H is too large to be a KIND

A side is longer than a PNG can have, the file of a BMP would be 4 GiB or more, a side of a JPEG or of a GIF is over 65,535, or a side of a WebP is over 16,384.

cannot write PATH: REASON

"encode_file" could not make its new file, write it or rename it. REASON is the system's own.

cannot write a path with a zero byte in it

CALLING FROM C

An extension written in C can ask for what "decode", "decode_file", "info", "encode" and "encode_file" give with no Perl call in between, and links nothing to do it. It is given the pixels where they are, with no copy made of them, and a picture is written from its own pixels where they are. It compiles against one header, imgpix_abi.h, which is installed with this module, and is handed a table of functions when it loads.

Its Makefile.PL finds the header through ExtUtils::Depends:

use ExtUtils::MakeMaker;
use ExtUtils::Depends;

my $pkg = ExtUtils::Depends->new('My::Module', 'Image::Pixels');

WriteMakefile(
    NAME               => 'My::Module',
    VERSION_FROM       => 'lib/My/Module.pm',
    CONFIGURE_REQUIRES => { 'ExtUtils::Depends' => '0.404', 'Image::Pixels' => '0.01' },
    PREREQ_PM          => { 'Image::Pixels' => '0.01' },
    $pkg->get_makefile_vars,
);

And this is the whole of its Module.xs, with one function, which counts the pixels of a picture that are wholly clear:

#include "EXTERN.h"
#include "perl.h"
#include "XSUB.h"
#include "imgpix_abi.h"

static const imgpix_abi *IMGPIX = NULL;

MODULE = My::Module  PACKAGE = My::Module

BOOT:
{
    SV *at = eval_pv(Perl_form(aTHX_
        "require Image::Pixels; Image::Pixels::_abi_ptr(%lu, %lu)",
        (unsigned long)IMGPIX_ABI_VERSION,
        (unsigned long)sizeof(imgpix_abi)), TRUE);
    IMGPIX = INT2PTR(const imgpix_abi *, SvUV(at));
}

SV *
clear_pixels(data)
    SV *data
  PREINIT:
    STRLEN len;
    const char *bytes;
    imgpix_abi_pixels picture;
    size_t nth, count;
    UV clear = 0;
    int code;
  CODE:
    if (!IMGPIX)
        croak("My::Module did not load");
    bytes = SvPVbyte(data, len);
    code  = (IMGPIX->decode)((const uint8_t *)bytes, len, IMGPIX_ABI_MOST, &picture);
    if (code == IMGPIX_ABI_E_IMAGE)
        XSRETURN_UNDEF;
    if (code != IMGPIX_ABI_OK)
        croak("%s", (IMGPIX->error_message)(code));
    count = (size_t)picture.width * picture.height;
    for (nth = 0; nth < count; nth++)
        clear += picture.rgba[4 * nth + 3] == 0;
    (IMGPIX->free_pixels)(&picture);
    RETVAL = newSVuv(clear);
  OUTPUT:
    RETVAL

The two numbers it asks with are the version of the table that its header has and the size the table has in that header. Where this module's table is of an earlier version, or is shorter, the call croaks naming both numbers and the extension does not load. Any later table is handed over. The table only ever grows at its end: a member is never taken out of it, moved or given another meaning, and a release that adds one adds one to the version.

Every function that calls through the table tests the pointer first, as clear_pixels does. Perl is given all the functions of an extension before its BOOT block runs. So where the load is refused, the functions are still there for a program that caught the refusal, and one that went through the table then would follow a pointer that was never set. An extension with many such functions can set the pointer, before it asks, to a table of its own whose every member croaks, and then test nowhere.

The brackets in (IMGPIX->decode)(...) keep a member's name from being read as a macro of the same name, which perl's own headers make of a number of ordinary names.

Version 1 of the table has ten members:

decode             the pixels of a picture, from the bytes of its file
decode_file        the same for a file, read whole
free_pixels        gives those pixels back
info               the kind and the size, with nothing drawn
inflate            a zlib stream unpacked into room of an exact size
format_name        the word for a kind
error_message      words for an answer
encode             the bytes of a file, from pixels
encode_file        the same, written to a file
free_bytes         gives those bytes back

None takes anything of perl's and none calls Perl. None keeps a pointer after it returns. A NULL where bytes or a structure are needed is refused. One that makes something answers 0, or one of five numbers that the header names: the caller's mistake, more pixels than were allowed or no memory for them, bytes that are not a picture drawn here, a file that could not be read, and a file that could not be written. The header says what each takes and answers.

Pixels asked for that way are this module's own memory. They are given back through the table, which overwrites them first. So an extension that must not leave a picture lying in memory asks that way, and not through "decode". The bytes of a file made that way are this module's memory as well, and are overwritten and given back in the same way.

AUTHOR

LNATION <email@lnation.org>

BUGS

Please report any bugs or feature requests to bug-image-pixels at rt.cpan.org, or through the web interface at https://rt.cpan.org/NoAuth/ReportBug.html?Queue=Image-Pixels.

SUPPORT

You can find documentation for this module with the perldoc command.

perldoc Image::Pixels

LICENSE AND COPYRIGHT

This software is Copyright (c) 2026 by LNATION <email@lnation.org>.

This is free software, licensed under:

The Artistic License 2.0 (GPL Compatible)