Appendix A. A Simple PNG Decoder in Perl

The PNGObject Perl module will only parse the critical chunks, and will skip (and identify) ancillary chunks. You can use the PNGObject module to dump a listing of the chunks of a PNG file. It can be used like this:

use PNGObject;
my $png = new PNGObject;
$png->readPNG('some_image.png');

Here is the code for a simple PNG decoder module:

# -*- Perl -*- # PNGObject.pm # A Perl module that will decode the chunks of a PNG formatted file and # dump a printout of the various fields. # package PNGObject; use strict; # This hash defines the ordering of fields within the critical chunks # my %png_fields = ( # Critical chunks # header => [qw( width height bit_depth color_type compression filter interlace )], palette => [qw( red green blue )], image_data => [qw( data )] ); # This will create a string which can be used for # valid signature comparisons # my $png_signature = pack "H16", "89504E470D0A1A0A"; # A list of the standard ancillary chunks for use in a later # regular expression. # my $ancillary_chunks = join "|", qw( bKGD cHRM gAMA hIST pHYs sBIT tEXT tIME tRNS oFFs sCAL tIME ); # This hash may be referenced to determine the length of # each field (in bytes) for a particular chunk. # my %png_format = ( # Every chunk has an 8 byte header and a 4 byte trailer # all => { 'length' => 4, type => 4, # Chunk-specific data goes here # crc => 4 }, header => { width => 4, height => 4, bit_depth => 1, color_type => 1, compression => 1, filter => 1, interlace ...

Get Programming Web Graphics with Perl and GNU Softwar now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.