.\" -*- mode: troff; coding: utf-8 -*- .\" Automatically generated by Pod::Man 5.01 (Pod::Simple 3.43) .\" .\" Standard preamble: .\" ======================================================================== .de Sp \" Vertical space (when we can't use .PP) .if t .sp .5v .if n .sp .. .de Vb \" Begin verbatim text .ft CW .nf .ne \\$1 .. .de Ve \" End verbatim text .ft R .fi .. .\" \*(C` and \*(C' are quotes in nroff, nothing in troff, for use with C<>. .ie n \{\ . ds C` "" . ds C' "" 'br\} .el\{\ . ds C` . ds C' 'br\} .\" .\" Escape single quotes in literal strings from groff's Unicode transform. .ie \n(.g .ds Aq \(aq .el .ds Aq ' .\" .\" If the F register is >0, we'll generate index entries on stderr for .\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index .\" entries marked with X<> in POD. Of course, you'll have to process the .\" output yourself in some meaningful fashion. .\" .\" Avoid warning from groff about undefined register 'F'. .de IX .. .nr rF 0 .if \n(.g .if rF .nr rF 1 .if (\n(rF:(\n(.g==0)) \{\ . if \nF \{\ . de IX . tm Index:\\$1\t\\n%\t"\\$2" .. . if !\nF==2 \{\ . nr % 0 . nr F 2 . \} . \} .\} .rr rF .\" ======================================================================== .\" .IX Title "Imager::Cookbook 3pm" .TH Imager::Cookbook 3pm 2024-04-13 "perl v5.38.2" "User Contributed Perl Documentation" .\" For nroff, turn off justification. Always turn off hyphenation; it makes .\" way too many mistakes in technical documents. .if n .ad l .nh .SH NAME Imager::Cookbook \- recipes working with Imager .SH DESCRIPTION .IX Header "DESCRIPTION" Various simple and not so simple ways to do things with Imager. .SH FILES .IX Header "FILES" This is described in detail in Imager::Files. .SS "Reading an image from a file" .IX Subsection "Reading an image from a file" .Vb 1 \& my $image = Imager\->new; \& \& $image\->read(file=>$filename) or die $image\->errstr; .Ve .PP Or: .PP .Vb 2 \& my $image = Imager\->new(file => $filename) \& or die Imager\->errstr; .Ve .PP See Imager::Files. .SS "Writing an image to a file" .IX Subsection "Writing an image to a file" .Vb 1 \& $image\->write(file=>$filename) or die $image\->errstr; .Ve .SS "Write an animated GIF" .IX Subsection "Write an animated GIF" .Vb 4 \& # build an array of images to use in the gif \& my @images; \& # synthesize the images or read them from files, it doesn\*(Aqt matter \& ... \& \& # write the gif \& Imager\->write_multi({ file=>$filename, type=>\*(Aqgif\*(Aq }, @images) \& or die Imager\->errstr; .Ve .PP See "Writing an animated GIF" in Imager::Files for a more detailed example. .SS "Reading multiple images from one file" .IX Subsection "Reading multiple images from one file" Some formats, like GIF and TIFF support multiple images per file. Use the \fBread_multi()\fR method to read them: .PP .Vb 2 \& my @images = Imager\->read_multi(file=>$filename) \& or die Imager\->errstr; .Ve .SS "Converting from one file format to another" .IX Subsection "Converting from one file format to another" This is as simple as reading the original file and writing the new file, for single images: .PP .Vb 7 \& my $image = Imager\->new; \& # Imager auto\-detects the input file type \& $image\->read(file => $input_filename) \& or die $image\->errstr; \& # Imager derives the output file format from the filename \& $image\->write(file => $output_filename) \& or die $image\->errstr; \& \& # or you can supply a type parameter: \& $image\->write(file => $output_filename, type => \*(Aqgif\*(Aq) \& or die $image\->errstr; .Ve .PP The main issue that can occur with this is if the input file has transparency and the output file format doesn't support that. This can be a problem when converting from GIF files to JPEG files for example. .PP By default, if the output format doesn't support transparency, Imager will compose the image onto a black background. You can override that by supplying an \f(CW\*(C`i_background\*(C'\fR option to \f(CWwrite()\fR or \&\f(CWwrite_multi()\fR: .PP .Vb 2 \& $image\->write(file => "foo.jpg", i_background => "#808080") \& or die $image\->errstr; .Ve .PP Some formats support multiple files, so if you want to convert from say TIFF to JPEG, you'll need multiple output files: .PP .Vb 7 \& my @images = Imager\->read_multi(file => \*(Aqinput.tif\*(Aq) \& or die Imager\->errstr; \& my $index = 1; \& for my $image (@images) { \& $image\->write(file => sprintf(\*(Aqoutput%02d.jpg\*(Aq, $index++)) \& or die $image\->errstr; \& } .Ve .SS "Transparent PNG" .IX Subsection "Transparent PNG" To save to a transparent PNG (or GIF or TIFF) you need to start with an image with transparency. .PP To make a transparent image, create an image object with 2 or 4 channels: .PP .Vb 2 \& # RGB with alpha channel \& my $rgba = Imager\->new(xsize => $width, ysize => $height, channels => 4); \& \& # Gray with alpha channel \& my $graya = Imager\->new(xsize => $width, ysize => $height, channels => 2); .Ve .PP By default, the created image will be transparent. .PP Otherwise, if you have an existing image file with transparency, simply read it, and the transparency will be preserved. .SH "IMAGE SYNTHESIS" .IX Header "IMAGE SYNTHESIS" .SS "Creating an image" .IX Subsection "Creating an image" To create a simple RGB image, supply the image width and height to the \&\fBnew()\fR method: .PP .Vb 1 \& my $rgb = Imager\->new(xsize=>$width, ysize=>$height); .Ve .PP If you also want an alpha channel: .PP .Vb 1 \& my $rgb_alpha = Imager\->new(xsize=>$width, ysize=>$height, channels=>4); .Ve .PP To make a gray-scale image: .PP .Vb 1 \& my $gray = Imager\->new(xsize=>$width, ysize=>$height, channels=>1); .Ve .PP and a gray-scale image with an alpha channel: .PP .Vb 1 \& my $gray_alpha = Imager\->new(xsize=>$width, ysize=>$height, channels=>2); .Ve .PP When a new image is created this way all samples are set to zero \- black for 1 or 3 channel images, transparent black for 2 or 4 channel images. .PP You can also create paletted images and images with more than 8\-bits per channel, see Imager::ImageTypes for more details. .SS "Setting the background of a new image" .IX Subsection "Setting the background of a new image" To set the background of a new image to a solid color, use the \fBbox()\fR method with no limits, and \f(CW\*(C`filled=>1\*(C'\fR: .PP .Vb 1 \& $image\->box(filled=>1, color=>$color); .Ve .PP As always, a color can be specified as an Imager::Color object: .PP .Vb 2 \& my $white = Imager::Color\->new(255, 255, 255); \& $image\->box(filled=>1, color=>$white); .Ve .PP or you supply any single scalar that Imager::Color's \fBnew()\fR method accepts as a color description: .PP .Vb 3 \& $image\->box(filled=>1, color=>\*(Aqwhite\*(Aq); \& $image\->box(filled=>1, color=>\*(Aq#FF0000\*(Aq); \& $image\->box(filled=>1, color=>[ 255, 255, 255 ]); .Ve .PP You can also fill the image with a fill object: .PP .Vb 4 \& use Imager::Fill; \& # create the fill object \& my $fill = Imager::Fill\->new(hatch=>\*(Aqcheck1x1\*(Aq) \& $image\->box(fill=>$fill); \& \& # let Imager create one automatically \& $image\->box(fill=>{ hatch=>\*(Aqcheck1x1\*(Aq }); .Ve .PP See Imager::Fill for information on Imager's fill objects. .SS "Create an image from raw RGB data" .IX Subsection "Create an image from raw RGB data" If your data matches the layout supported by Imager's "RAW" in Imager::Files file support closely enough, you can simply read the data as if it was a raw file: .PP .Vb 10 \& my $img = Imager\->new( \& ( \& filetype => "raw", \& xsize => $width, \& ysize => $height, \& # stored as RGBXRGBX where X is dropped \& raw_interleave => 0, \& raw_datachannels => 4, \& raw_storechannels => 3, \& ); .Ve .PP If the channel order doesn't match you can further use the "\fBcombine()\fR" in Imager::Transformations method to extract the channels in the correct order, eg. if the source data above was in \f(CW\*(C`BGRX\*(C'\fR format instead of \f(CW\*(C`RGBX\*(C'\fR: .PP .Vb 2 \& my $img2 = $im\->combine(src => [ $img, $img, $img ], \& channels => [ 2, 1, 0 ]); .Ve .PP Adapted from perl monks . .PP For more control you can use the \fBsetsamples()\fR method to set pixels directly to the image: .PP .Vb 10 \& # for AGBR data in $data \& my $img = Imager\->new(xsize => $width, ysize => $height, channels => 4); \& my $rowbytes = $width * 4; \& my @chans = [ 3, 1, 2, 0 ]; \& for my $row (0 .. $height) { \& $img\->setsamples \& ( \& y => $row, \& data => $data, \& offset => $rowbytes * $row, \& channels => \e@chans, \& type => \*(Aq8bit\*(Aq, \& ); \& } .Ve .SH "WORLD WIDE WEB" .IX Header "WORLD WIDE WEB" As with any CGI script it's up to you to validate data and set limits on any parameters supplied to Imager. .PP For example, if you allow the caller to set the size of an output image you should limit the size to prevent the client from specifying an image size that will consume all available memory. .PP This is beside any other controls you need over access to data. .PP See CGI for a module useful for processing CGI submitted data. .SS "Returning an image from a CGI script" .IX Subsection "Returning an image from a CGI script" This is similar to writing to a file, but you also need to supply the information needed by the web browser to identify the file format: .PP .Vb 6 \& my $img = ....; # create the image and generate the contents \& ++$|; # make sure the content type isn\*(Aqt buffered \& print "Content\-Type: image/png\en\en"; \& binmode STDOUT; \& $img\->write(fd=>fileno(STDOUT), type=>\*(Aqpng\*(Aq) \& or die $img\->errstr; .Ve .PP You need to set the Content-Type header depending on the file format you send to the web browser. .PP If you want to supply a content-length header, write the image to a scalar as a buffer: .PP .Vb 8 \& my $img = ....; # create the image and generate the contents \& my $data; \& $img\->write(type=>\*(Aqpng\*(Aq, data=>\e$data) \& or die $img\->errstr; \& print "Content\-Type: image/png\en"; \& print "Content\-Length: ",length($data),"\en\en"; \& binmode STDOUT; \& print $data; .Ve .PP See \f(CW\*(C`samples/samp\-scale.cgi\*(C'\fR and \f(CW\*(C`samples/samp\-image.cgi\*(C'\fR for a couple of simple examples of producing an image from CGI. .SS "Inserting a CGI image in a page" .IX Subsection "Inserting a CGI image in a page" There's occasionally confusion on how to display an image generated by Imager in a page generated by a CGI. .PP Your web browser handles this process as two requests, one for the HTML page, and another for the image itself. .PP Each request needs to perform validation since an attacker can control the values supplied to both requests. .PP How you make the data available to the image generation code depends on your application. .PP See \f(CW\*(C`samples/samp\-form.cgi\*(C'\fR and \f(CW\*(C`samples/samp\-image.cgi\*(C'\fR in the Imager distribution for one approach. The POD in \f(CW\*(C`samp\-form.cgi\*(C'\fR also discusses some of the issues involved. .SS "Parsing an image posted via CGI" .IX Subsection "Parsing an image posted via CGI" \&\f(CW\*(C`WARNING\*(C'\fR: file format attacks have become a common attack vector, make sure you have up to date image file format libraries, otherwise trying to parse uploaded files, whether with Imager or some other tool, may result in a remote attacker being able to run their own code on your system. .PP If your HTML form uses the correct magic, it can upload files to your CGI script, in particular, you need to use \f(CW\*(C` method="post" \*(C'\fR and \&\f(CW\*(C`enctype="multipart/form\-data"\*(C'\fR in the \f(CW\*(C`form\*(C'\fR tag, and use \&\f(CW\*(C`type="file"\*(C'\fR in the \f(CW\*(C`input\*(C'\fR, for example: .PP .Vb 5 \&
\& \& \&
.Ve .PP To process the form: .IP 1. 4 first check that the user supplied a file .IP 2. 4 get the file handle .IP 3. 4 have Imager read the image .PP .Vb 9 \& # returns the client\*(Aqs name for the file, don\*(Aqt open this locally \& my $cgi = CGI\->new; \& # 1. check the user supplied a file \& my $filename = $cgi\->param(\*(Aqmyimage\*(Aq); \& if ($filename) { \& # 2. get the file handle \& my $fh = $cgi\->upload(\*(Aqmyimage\*(Aq); \& if ($fh) { \& binmode $fh; \& \& # 3. have Imager read the image \& my $img = Imager\->new; \& if ($img\->read(fh=>$fh)) { \& # we can now process the image \& } \& } \& # else, you probably have an incorrect form or input tag \& } \& # else, the user didn\*(Aqt select a file .Ve .PP See \f(CW\*(C`samples/samp\-scale.cgi\*(C'\fR and \f(CW\*(C`samples/samp\-tags.cgi\*(C'\fR in the Imager distribution for example code. .PP You may also want to set limits on the size of the image read, using Imager's \f(CW\*(C`set_file_limits\*(C'\fR method, documented in "\fBset_file_limits()\fR" in Imager::Files. For example: .PP .Vb 2 \& # limit to 10 million bytes of memory usage \& Imager\->set_file_limits(bytes => 10_000_000); \& \& # limit to 1024 x 1024 \& Imager\->set_file_limits(width => 1024, height => 1024); .Ve .SH DRAWING .IX Header "DRAWING" .SS "Adding a border to an image" .IX Subsection "Adding a border to an image" First make a new image with space for the border: .PP .Vb 6 \& my $border_width = ...; \& my $border_height = ...; \& my $out = Imager\->new(xsize => $source\->getwidth() + 2 * $border_width, \& ysize => $source\->getheight() + 2 * $border_height, \& bits => $source\->bits, \& channels => $source\->getchannels); .Ve .PP Then paste the source image into the new image: .PP .Vb 3 \& $out\->paste(left => $border_width, \& top => $border_height, \& img => $source); .Ve .PP Whether you draw the border before or after pasting the original image depends on whether you want the border to overlap the image, for example a semi-transparent border drawn after pasting the source image could overlap the edge without hiding it. .PP If you want a solid border you could just fill the image before pasting the source for simplicity: .PP .Vb 4 \& $out\->box(filled=>1, color=>\*(Aqred\*(Aq); \& $out\->paste(left => $border_width, \& top => $border_height, \& img => $source); .Ve .SH TEXT .IX Header "TEXT" .SS "Drawing text" .IX Subsection "Drawing text" .SS "Aligning text" .IX Subsection "Aligning text" .SS "Measuring text" .IX Subsection "Measuring text" .SS "Word wrapping text" .IX Subsection "Word wrapping text" .SS "Shearing (slanting) or Rotating text" .IX Subsection "Shearing (slanting) or Rotating text" This requires that you have Imager installed with FreeType 2.x support installed, and that the font be created using the FreeType 2.x driver, for example: .PP .Vb 1 \& my $font = Imager::Font\->new(file=>$fontfile, type=>\*(Aqft2\*(Aq); .Ve .PP First you need a transformation matrix, for shearing that could be: .PP .Vb 4 \& my $angle_in_radians = ...; \& my $tan_angle = sin($angle_rads) / cos($angle_rads); \& # shear horizontally, supply this as y instead to do it vertically \& my $matrix = Imager::Matrix2d\->shear(x=>$tan_angle); .Ve .PP For rotation that would be: .PP .Vb 1 \& my $matrix = Imager::Matrix2d\->rotate(radians => $angle_in_radians); .Ve .PP or: .PP .Vb 1 \& my $matrix = Imager::Matrix2d\->rotate(degrees => $angle_in_degrees); .Ve .PP Feed that to the font object: .PP .Vb 1 \& $font\->transform(matrix => $matrix); .Ve .PP and draw the text as normal: .PP .Vb 5 \& $image\->string(string => $text, \& x => $where_x, \& y => $where_y, \& color => $color, \& font => $font); .Ve .PP See samples/slant_text.pl for a comprehensive example, including calculating the transformed bounding box to create an image to fit the transformed text into. .SH "IMAGE TRANSFORMATION" .IX Header "IMAGE TRANSFORMATION" .SS "Shearing an image" .IX Subsection "Shearing an image" .SS "Convert to gray-scale" .IX Subsection "Convert to gray-scale" To convert an RGB image to a gray-scale image, use the convert method: .PP .Vb 1 \& my $grey = $image\->convert(preset => \*(Aqgray\*(Aq); .Ve .PP \&\fBconvert()\fR returns a new image. .PP See: "Color transformations" in Imager::Transformations .SH METADATA .IX Header "METADATA" .SS "Image format" .IX Subsection "Image format" When Imager reads a file it does a magic number check to determine the file type, so \f(CW\*(C`foo.png\*(C'\fR could actually be a GIF image, and Imager will read it anyway. .PP You can check the actual format of the image by looking at the \&\f(CW\*(C`i_format\*(C'\fR tag. .PP .Vb 1 \& my $format = $image\->tags(name=>\*(Aqi_format\*(Aq); .Ve .SS "Image spatial resolution" .IX Subsection "Image spatial resolution" Most image file formats store information about the physical size of the pixels, though in some cases that information isn't useful. .PP Imager stores this information in the tags \f(CW\*(C`i_xres\*(C'\fR and \f(CW\*(C`i_yres\*(C'\fR, and this is always stored in dots per inch. .PP Some formats, including TIFF and JPEG allow you to change the units spatial resolution information is stored in, if you set the tag that changes this the Imager will convert \f(CW\*(C`i_xres\*(C'\fR and \f(CW\*(C`i_yres\*(C'\fR to those units when it writes the file. .PP For example to set the resolution to 300 dpi: .PP .Vb 2 \& $image\->settag(name => \*(Aqi_xres\*(Aq, value => 300); \& $image\->settag(name => \*(Aqi_yres\*(Aq, value => 300); .Ve .PP If you want the file format to store the resolution in some other unit, for example you can write a TIFF file that stores the resolution in pixels per centimeter, you would do: .PP .Vb 4 \& # 150 pixels/cm \& $image\->settag(name => \*(Aqi_xres\*(Aq, value => 150 * 2.54); \& $image\->settag(name => \*(Aqi_yres\*(Aq, value => 150 * 2.54); \& $image\->settag(name => \*(Aqtiff_resolutionunit\*(Aq, value => 3); .Ve .PP Keywords: DPI .SH "IMAGE MANIPULATION" .IX Header "IMAGE MANIPULATION" .SS "Replacing a color with transparency" .IX Xref "replacing colors" .IX Subsection "Replacing a color with transparency" To replace a color with transparency you can use the "\fBdifference()\fR" in Imager::Filters method. .PP .Vb 5 \& # make a work image the same size as our input \& my $work = Imager\->new(xsize => $in\->getwidth, ysize => $in\->getheight, \& channels => $in\->getchannels); \& # and fill it with the color we want transparent \& $work\->box(filled => 1, color => $color); \& \& # get an image with that color replaced with transparent black \& my $out = $work\->difference(other => $in); .Ve .SH "SPECIAL EFFECTS" .IX Header "SPECIAL EFFECTS" .SS "Drop Shadows" .IX Xref "drop shadow effects, drop shadow" .IX Subsection "Drop Shadows" This can be used for a glow effect as well. .PP First create a new image, either with an alpha channel (if you want transparency behind the shadow) or without, if you want a background color: .PP .Vb 8 \& my $out = Imager\->new \& ( \& xsize => $shadow_size * 2 + $src\->getwidth, \& ysize => $shadow_size * 2 + $src\->getheight, \& channels => 4, \& ); \& # fill it with your background color, if you want one \& # $out\->box(filled => 1, color => $back_color); .Ve .PP Make a work image to render the shadow on: .PP .Vb 6 \& my $shadow_work = Imager\->new \& ( \& xsize => $back\->getwidth, \& ysize => $back\->getheight, \& channels => 1, \& ); .Ve .PP Extract the alpha channel from the source image, first the alpha version: .PP .Vb 1 \& my $alpha = $src\->convert(preset => "alpha"); .Ve .PP and draw that on the work shadow: .PP .Vb 6 \& $shadow_work\->paste \& ( \& src => $slpha, \& left => $shadow_size, \& top => $shadow_size, \& ); .Ve .PP otherwise just draw a box for the non-alpha source: .PP .Vb 9 \& $shadow_work\->box \& ( \& filled => 1, \& color => [ 255 ], \& xmin => $shadow_size, \& ymin => $shadow_size, \& xmax => $shadow_size + $src\->getwidth() \- 1, \& ymax => $shadow_size + $src\->getheight() \- 1, \& ); .Ve .PP Blur the work shadow: .PP .Vb 1 \& $shadow_work\->filter(type => "gaussian", stddev => $shadow_size); .Ve .PP Convert it to an RGB image with alpha: .PP .Vb 7 \& $shadow_work = $shadow_work\->convert \& ( \& matrix => [ [ 0, $red / 255 ], \& [ 0, $green / 255 ], \& [ 0, $blue / 255 ], \& [ 1 ] ] \& ); .Ve .PP Draw that on the output image: .PP .Vb 1 \& $out\->rubthrough(src => $shadow_work); .Ve .PP Draw our original image on the output image, perhaps with an offset: .PP .Vb 6 \& $out\->rubthrough \& ( \& src => $src, \& tx => $shadow_size + $x_offset, \& ty => $shadow_size + $y_offset, \& ); .Ve .PP See \fIsamples/drop_shadow.pl\fR for an example of this recipe. .SH AUTHOR .IX Header "AUTHOR" Tony Cook .SH "SEE ALSO" .IX Header "SEE ALSO" Imager, Imager::Files, Imager::Draw.