Debian Codegraph @

lib/Imager/Cookbook.pod

raw
1 =head1 NAME
2
3 Imager::Cookbook - recipes working with Imager
4
5 =head1 DESCRIPTION
6
7 Various simple and not so simple ways to do things with Imager.
8
9 =head1 FILES
10
11 This is described in detail in L<Imager::Files>.
12
13 =head2 Reading an image from a file
14
15 my $image = Imager->new;
16
17 $image->read(file=>$filename) or die $image->errstr;
18
19 Or:
20
21 my $image = Imager->new(file => $filename)
22 or die Imager->errstr;
23
24 See L<Imager::Files>.
25
26 =head2 Writing an image to a file
27
28 $image->write(file=>$filename) or die $image->errstr;
29
30 =head2 Write an animated GIF
31
32 # build an array of images to use in the gif
33 my @images;
34 # synthesize the images or read them from files, it doesn't matter
35 ...
36
37 # write the gif
38 Imager->write_multi({ file=>$filename, type=>'gif' }, @images)
39 or die Imager->errstr;
40
41 See L<Imager::Files/"Writing an animated GIF"> for a more detailed
42 example.
43
44 =head2 Reading multiple images from one file
45
46 Some formats, like GIF and TIFF support multiple images per file. Use
47 the L<read_multi()|Imager::Files> method to read them:
48
49 my @images = Imager->read_multi(file=>$filename)
50 or die Imager->errstr;
51
52 =head2 Converting from one file format to another
53
54 This is as simple as reading the original file and writing the new
55 file, for single images:
56
57 my $image = Imager->new;
58 # Imager auto-detects the input file type
59 $image->read(file => $input_filename)
60 or die $image->errstr;
61 # Imager derives the output file format from the filename
62 $image->write(file => $output_filename)
63 or die $image->errstr;
64
65 # or you can supply a type parameter:
66 $image->write(file => $output_filename, type => 'gif')
67 or die $image->errstr;
68
69 The main issue that can occur with this is if the input file has
70 transparency and the output file format doesn't support that. This
71 can be a problem when converting from GIF files to JPEG files for
72 example.
73
74 By default, if the output format doesn't support transparency, Imager
75 will compose the image onto a black background. You can override that
76 by supplying an C<i_background> option to C<write()> or
77 C<write_multi()>:
78
79 $image->write(file => "foo.jpg", i_background => "#808080")
80 or die $image->errstr;
81
82 Some formats support multiple files, so if you want to convert from
83 say TIFF to JPEG, you'll need multiple output files:
84
85 my @images = Imager->read_multi(file => 'input.tif')
86 or die Imager->errstr;
87 my $index = 1;
88 for my $image (@images) {
89 $image->write(file => sprintf('output%02d.jpg', $index++))
90 or die $image->errstr;
91 }
92
93 =head2 Transparent PNG
94
95 To save to a transparent PNG (or GIF or TIFF) you need to start with
96 an image with transparency.
97
98 To make a transparent image, create an image object with 2 or 4
99 channels:
100
101 # RGB with alpha channel
102 my $rgba = Imager->new(xsize => $width, ysize => $height, channels => 4);
103
104 # Gray with alpha channel
105 my $graya = Imager->new(xsize => $width, ysize => $height, channels => 2);
106
107 By default, the created image will be transparent.
108
109 Otherwise, if you have an existing image file with transparency,
110 simply read it, and the transparency will be preserved.
111
112 =head1 IMAGE SYNTHESIS
113
114 =head2 Creating an image
115
116 To create a simple RGB image, supply the image width and height to the
117 new() method:
118
119 my $rgb = Imager->new(xsize=>$width, ysize=>$height);
120
121 If you also want an alpha channel:
122
123 my $rgb_alpha = Imager->new(xsize=>$width, ysize=>$height, channels=>4);
124
125 To make a gray-scale image:
126
127 my $gray = Imager->new(xsize=>$width, ysize=>$height, channels=>1);
128
129 and a gray-scale image with an alpha channel:
130
131 my $gray_alpha = Imager->new(xsize=>$width, ysize=>$height, channels=>2);
132
133 When a new image is created this way all samples are set to zero -
134 black for 1 or 3 channel images, transparent black for 2 or 4 channel
135 images.
136
137 You can also create paletted images and images with more than 8-bits
138 per channel, see L<Imager::ImageTypes> for more details.
139
140 =head2 Setting the background of a new image
141
142 To set the background of a new image to a solid color, use the box()
143 method with no limits, and C<< filled=>1 >>:
144
145 $image->box(filled=>1, color=>$color);
146
147 As always, a color can be specified as an L<Imager::Color> object:
148
149 my $white = Imager::Color->new(255, 255, 255);
150 $image->box(filled=>1, color=>$white);
151
152 or you supply any single scalar that Imager::Color's new() method
153 accepts as a color description:
154
155 $image->box(filled=>1, color=>'white');
156 $image->box(filled=>1, color=>'#FF0000');
157 $image->box(filled=>1, color=>[ 255, 255, 255 ]);
158
159 You can also fill the image with a fill object:
160
161 use Imager::Fill;
162 # create the fill object
163 my $fill = Imager::Fill->new(hatch=>'check1x1')
164 $image->box(fill=>$fill);
165
166 # let Imager create one automatically
167 $image->box(fill=>{ hatch=>'check1x1' });
168
169 See L<Imager::Fill> for information on Imager's fill objects.
170
171 =head2 Create an image from raw RGB data
172
173 If your data matches the layout supported by Imager's
174 L<Imager::Files/RAW> file support closely enough, you can simply read
175 the data as if it was a raw file:
176
177 my $img = Imager->new(
178 (
179 filetype => "raw",
180 xsize => $width,
181 ysize => $height,
182 # stored as RGBXRGBX where X is dropped
183 raw_interleave => 0,
184 raw_datachannels => 4,
185 raw_storechannels => 3,
186 );
187
188 If the channel order doesn't match you can further use the
189 L<Imager::Transformations/combine()> method to extract the channels in
190 the correct order, eg. if the source data above was in C<BGRX> format
191 instead of C<RGBX>:
192
193 my $img2 = $im->combine(src => [ $img, $img, $img ],
194 channels => [ 2, 1, 0 ]);
195
196 Adapted from L<perl monks|https://perlmonks.org/?node_id=11139983>.
197
198 For more control you can use the setsamples() method to set pixels
199 directly to the image:
200
201 # for AGBR data in $data
202 my $img = Imager->new(xsize => $width, ysize => $height, channels => 4);
203 my $rowbytes = $width * 4;
204 my @chans = [ 3, 1, 2, 0 ];
205 for my $row (0 .. $height) {
206 $img->setsamples
207 (
208 y => $row,
209 data => $data,
210 offset => $rowbytes * $row,
211 channels => \@chans,
212 type => '8bit',
213 );
214 }
215
216 =head1 WORLD WIDE WEB
217
218 As with any CGI script it's up to you to validate data and set limits
219 on any parameters supplied to Imager.
220
221 For example, if you allow the caller to set the size of an output
222 image you should limit the size to prevent the client from specifying
223 an image size that will consume all available memory.
224
225 This is beside any other controls you need over access to data.
226
227 See L<CGI> for a module useful for processing CGI submitted data.
228
229 =head2 Returning an image from a CGI script
230
231 This is similar to writing to a file, but you also need to supply the
232 information needed by the web browser to identify the file format:
233
234 my $img = ....; # create the image and generate the contents
235 ++$|; # make sure the content type isn't buffered
236 print "Content-Type: image/png\n\n";
237 binmode STDOUT;
238 $img->write(fd=>fileno(STDOUT), type=>'png')
239 or die $img->errstr;
240
241 You need to set the Content-Type header depending on the file format
242 you send to the web browser.
243
244 If you want to supply a content-length header, write the image to a
245 scalar as a buffer:
246
247 my $img = ....; # create the image and generate the contents
248 my $data;
249 $img->write(type=>'png', data=>\$data)
250 or die $img->errstr;
251 print "Content-Type: image/png\n";
252 print "Content-Length: ",length($data),"\n\n";
253 binmode STDOUT;
254 print $data;
255
256 See C<samples/samp-scale.cgi> and C<samples/samp-image.cgi> for a
257 couple of simple examples of producing an image from CGI.
258
259 =head2 Inserting a CGI image in a page
260
261 There's occasionally confusion on how to display an image generated by
262 Imager in a page generated by a CGI.
263
264 Your web browser handles this process as two requests, one for the
265 HTML page, and another for the image itself.
266
267 Each request needs to perform validation since an attacker can control
268 the values supplied to both requests.
269
270 How you make the data available to the image generation code depends
271 on your application.
272
273 See C<samples/samp-form.cgi> and C<samples/samp-image.cgi> in the
274 Imager distribution for one approach. The POD in C<samp-form.cgi>
275 also discusses some of the issues involved.
276
277 =head2 Parsing an image posted via CGI
278
279 C<WARNING>: file format attacks have become a common attack vector,
280 make sure you have up to date image file format libraries, otherwise
281 trying to parse uploaded files, whether with Imager or some other
282 tool, may result in a remote attacker being able to run their own code
283 on your system.
284
285 If your HTML form uses the correct magic, it can upload files to your
286 CGI script, in particular, you need to use C< method="post" > and
287 C<enctype="multipart/form-data"> in the C<form> tag, and use
288 C<type="file"> in the C<input>, for example:
289
290 <form action="/cgi-bin/yourprogram" method="post"
291 enctype="multipart/form-data">
292 <input type="file" name="myimage" />
293 <input type="submit value="Upload Image" />
294 </form>
295
296 To process the form:
297
298 =over
299
300 =item 1.
301
302 first check that the user supplied a file
303
304 =item 2.
305
306 get the file handle
307
308 =item 3.
309
310 have Imager read the image
311
312 =back
313
314 # returns the client's name for the file, don't open this locally
315 my $cgi = CGI->new;
316 # 1. check the user supplied a file
317 my $filename = $cgi->param('myimage');
318 if ($filename) {
319 # 2. get the file handle
320 my $fh = $cgi->upload('myimage');
321 if ($fh) {
322 binmode $fh;
323
324 # 3. have Imager read the image
325 my $img = Imager->new;
326 if ($img->read(fh=>$fh)) {
327 # we can now process the image
328 }
329 }
330 # else, you probably have an incorrect form or input tag
331 }
332 # else, the user didn't select a file
333
334 See C<samples/samp-scale.cgi> and C<samples/samp-tags.cgi> in the
335 Imager distribution for example code.
336
337 You may also want to set limits on the size of the image read, using
338 Imager's C<set_file_limits> method, documented in
339 L<Imager::Files/set_file_limits()>. For example:
340
341 # limit to 10 million bytes of memory usage
342 Imager->set_file_limits(bytes => 10_000_000);
343
344 # limit to 1024 x 1024
345 Imager->set_file_limits(width => 1024, height => 1024);
346
347 =head1 DRAWING
348
349 =head2 Adding a border to an image
350
351 First make a new image with space for the border:
352
353 my $border_width = ...;
354 my $border_height = ...;
355 my $out = Imager->new(xsize => $source->getwidth() + 2 * $border_width,
356 ysize => $source->getheight() + 2 * $border_height,
357 bits => $source->bits,
358 channels => $source->getchannels);
359
360 Then paste the source image into the new image:
361
362 $out->paste(left => $border_width,
363 top => $border_height,
364 img => $source);
365
366 Whether you draw the border before or after pasting the original image
367 depends on whether you want the border to overlap the image, for
368 example a semi-transparent border drawn after pasting the source image
369 could overlap the edge without hiding it.
370
371 If you want a solid border you could just fill the image before
372 pasting the source for simplicity:
373
374 $out->box(filled=>1, color=>'red');
375 $out->paste(left => $border_width,
376 top => $border_height,
377 img => $source);
378
379
380 =head1 TEXT
381
382 =head2 Drawing text
383
384 =head2 Aligning text
385
386 =head2 Measuring text
387
388 =head2 Word wrapping text
389
390 =head2 Shearing (slanting) or Rotating text
391
392 This requires that you have Imager installed with FreeType 2.x support
393 installed, and that the font be created using the FreeType 2.x driver,
394 for example:
395
396 my $font = Imager::Font->new(file=>$fontfile, type=>'ft2');
397
398 First you need a transformation matrix, for shearing that could be:
399
400 my $angle_in_radians = ...;
401 my $tan_angle = sin($angle_rads) / cos($angle_rads);
402 # shear horizontally, supply this as y instead to do it vertically
403 my $matrix = Imager::Matrix2d->shear(x=>$tan_angle);
404
405 For rotation that would be:
406
407 my $matrix = Imager::Matrix2d->rotate(radians => $angle_in_radians);
408
409 or:
410
411 my $matrix = Imager::Matrix2d->rotate(degrees => $angle_in_degrees);
412
413 Feed that to the font object:
414
415 $font->transform(matrix => $matrix);
416
417 and draw the text as normal:
418
419 $image->string(string => $text,
420 x => $where_x,
421 y => $where_y,
422 color => $color,
423 font => $font);
424
425 See samples/slant_text.pl for a comprehensive example, including
426 calculating the transformed bounding box to create an image to fit the
427 transformed text into.
428
429 =head1 IMAGE TRANSFORMATION
430
431 =head2 Shearing an image
432
433 =head2 Convert to gray-scale
434
435 To convert an RGB image to a gray-scale image, use the convert method:
436
437 my $grey = $image->convert(preset => 'gray');
438
439 convert() returns a new image.
440
441 See: L<Imager::Transformations/"Color transformations">
442
443 =head1 METADATA
444
445 =head2 Image format
446
447 When Imager reads a file it does a magic number check to determine the
448 file type, so C<foo.png> could actually be a GIF image, and Imager
449 will read it anyway.
450
451 You can check the actual format of the image by looking at the
452 C<i_format> tag.
453
454 my $format = $image->tags(name=>'i_format');
455
456 =head2 Image spatial resolution
457
458 Most image file formats store information about the physical size of
459 the pixels, though in some cases that information isn't useful.
460
461 Imager stores this information in the tags C<i_xres> and C<i_yres>,
462 and this is always stored in dots per inch.
463
464 Some formats, including TIFF and JPEG allow you to change the units
465 spatial resolution information is stored in, if you set the tag that
466 changes this the Imager will convert C<i_xres> and C<i_yres> to those
467 units when it writes the file.
468
469 For example to set the resolution to 300 dpi:
470
471 $image->settag(name => 'i_xres', value => 300);
472 $image->settag(name => 'i_yres', value => 300);
473
474 If you want the file format to store the resolution in some other
475 unit, for example you can write a TIFF file that stores the resolution
476 in pixels per centimeter, you would do:
477
478 # 150 pixels/cm
479 $image->settag(name => 'i_xres', value => 150 * 2.54);
480 $image->settag(name => 'i_yres', value => 150 * 2.54);
481 $image->settag(name => 'tiff_resolutionunit', value => 3);
482
483 Keywords: DPI
484
485 =head1 IMAGE MANIPULATION
486
487 =head2 Replacing a color with transparency
488 X<replacing colors>
489
490 To replace a color with transparency you can use the
491 L<Imager::Filters/difference()> method.
492
493 # make a work image the same size as our input
494 my $work = Imager->new(xsize => $in->getwidth, ysize => $in->getheight,
495 channels => $in->getchannels);
496 # and fill it with the color we want transparent
497 $work->box(filled => 1, color => $color);
498
499 # get an image with that color replaced with transparent black
500 my $out = $work->difference(other => $in);
501
502 =head1 SPECIAL EFFECTS
503
504 =head2 Drop Shadows
505 X<drop shadow> X<effects, drop shadow>
506
507 This can be used for a glow effect as well.
508
509 First create a new image, either with an alpha channel (if you want
510 transparency behind the shadow) or without, if you want a background
511 color:
512
513 my $out = Imager->new
514 (
515 xsize => $shadow_size * 2 + $src->getwidth,
516 ysize => $shadow_size * 2 + $src->getheight,
517 channels => 4,
518 );
519 # fill it with your background color, if you want one
520 # $out->box(filled => 1, color => $back_color);
521
522 Make a work image to render the shadow on:
523
524 my $shadow_work = Imager->new
525 (
526 xsize => $back->getwidth,
527 ysize => $back->getheight,
528 channels => 1,
529 );
530
531 Extract the alpha channel from the source image, first the alpha version:
532
533 my $alpha = $src->convert(preset => "alpha");
534
535 and draw that on the work shadow:
536
537 $shadow_work->paste
538 (
539 src => $slpha,
540 left => $shadow_size,
541 top => $shadow_size,
542 );
543
544 otherwise just draw a box for the non-alpha source:
545
546 $shadow_work->box
547 (
548 filled => 1,
549 color => [ 255 ],
550 xmin => $shadow_size,
551 ymin => $shadow_size,
552 xmax => $shadow_size + $src->getwidth() - 1,
553 ymax => $shadow_size + $src->getheight() - 1,
554 );
555
556 Blur the work shadow:
557
558 $shadow_work->filter(type => "gaussian", stddev => $shadow_size);
559
560 Convert it to an RGB image with alpha:
561
562 $shadow_work = $shadow_work->convert
563 (
564 matrix => [ [ 0, $red / 255 ],
565 [ 0, $green / 255 ],
566 [ 0, $blue / 255 ],
567 [ 1 ] ]
568 );
569
570 Draw that on the output image:
571
572 $out->rubthrough(src => $shadow_work);
573
574 Draw our original image on the output image, perhaps with an offset:
575
576 $out->rubthrough
577 (
578 src => $src,
579 tx => $shadow_size + $x_offset,
580 ty => $shadow_size + $y_offset,
581 );
582
583 See F<samples/drop_shadow.pl> for an example of this recipe.
584
585 =head1 AUTHOR
586
587 Tony Cook <[email protected]>
588
589 =head1 SEE ALSO
590
591 L<Imager>, L<Imager::Files>, L<Imager::Draw>.
592
593 =cut