How to Manipulate Images in Perl
Perl was built for text manipulation, but it also has external libraries for manipulating raster images. A popular library from which you can manipulate images is called "gd." Since GD is not written in Perl, you have to install a native library (a dll on Windows systems) and its perl "bindings." This is relatively easy, depending on which platform you're using.
Instructions
-
Install GD Using ActivePerl
-
1
Install GD and its bindings with the ppm command. The ppm command accesses the "Perl Package Manager," an ActiveState specific package manager designed for installing Perl modules on systems with the make command or a C compiler.
-
2
Start ppm from the command-line. This will launch a GUI program.
-
-
3
Click on the "View All Packages" button on the toolbar.
-
4
Search for GD in the search box. Right-click on the GD package and click on "Install."
Install GD Using CPAN
-
5
Use CPAN to install GD on a Linux system or another system with make and a C compiler.
-
6
Install the GD library in the manner required by your particular Perl distribution. This will differ depending on your distribution and is right in the distribution docs.
-
7
Install the GD Perl bindings by starting CPAN and typing the command "Install GD".
Manipulate Images in Perl
-
8
Create a new image to manipulate. Import the GD module and then create a new image by creating a new GD::Image object. Pass the constructor the dimensions for the image:
"use GD;$im = new GD::Image(200,200);" -
9
Create some colors by creating some color objects and storing them in variables. Color objects can be created as necessary, but it's useful to have a mnemonic for the colors you're going to use:
"$white = $im->colorAllocate(255,255,255);
$black = $im->colorAllocate(0,0,0);
$red = $im->colorAllocate(255,0,0);" -
10
Set a transparent color:
"$im->transparent($white);" -
11
Draw a background. Since the image needs a background color, you can use a filled Rectangle primitive to draw a background color:
"$im->filledRectangle(0,0,200,200,$white);" -
12
Draw whatever you want. The GD library has a number of drawing primitives, from points and lines to arcs, circles and polygons:
"$im->filledRectangle(50,50,150,150,$red);" -
13
Output the file. Here, the file is output on stdout, which should be piped to a file, but you can easily output to another file handle you've opened. Make sure the file handle is in binary mode before printing the png file to it:
"binmode STDOUT;
print $im->png;"
-
1
Tips & Warnings
GD can create PNG, JPEG and GIF images, as well as other formats.