File: Files.pod

package info (click to toggle)
libimager-perl 1.019%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 6,824 kB
  • sloc: perl: 32,886; ansic: 28,193; makefile: 52; cpp: 4
file content (2237 lines) | stat: -rw-r--r-- 60,870 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
=head1 NAME

Imager::Files - working with image files

=head1 SYNOPSIS

  use Imager;
  my $img = ...;
  $img->write(file=>$filename, type=>$type)
    or die "Cannot write: ",$img->errstr;

  # type is optional if we can guess the format from the filename
  $img->write(file => "foo.png")
    or die "Cannot write: ",$img->errstr;

  $img = Imager->new;
  $img->read(file=>$filename, type=>$type)
    or die "Cannot read: ", $img->errstr;

  # type is optional if we can guess the type from the file data
  # and we normally can guess
  $img->read(file => $filename)
    or die "Cannot read: ", $img->errstr;

  Imager->write_multi({ file=> $filename, ... }, @images)
    or die "Cannot write: ", Imager->errstr;

  my @imgs = Imager->read_multi(file=>$filename)
    or die "Cannot read: ", Imager->errstr;

  Imager->set_file_limits(width=>$max_width, height=>$max_height)

  my @read_types = Imager->read_types;
  my @write_types = Imager->write_types;

  # we can write/write_multi to things other than filenames
  my $data;
  $img->write(data => \$data, type => $type) or die;

  open my $fh, "+>:raw", ... ;
  $img->write(fh => $fh, type => $type) or die;

  $img->write(fd => fileno($fh), type => $type) or die;

  # some file types need seek callbacks too
  $img->write(callback => \&write_callback, type => $type) or die;

  # and similarly for read/read_multi
  $img->read(data => $data) or die;
  $img->read(fh => $fh) or die;
  $img->read(fd => fileno($fh)) or die;
  $img->read(callback => \&read_callback) or die;

  use Imager 0.68;
  my $img = Imager->new(file => $filename)
    or die Imager->errstr;

  Imager->add_file_magic(name => $name, bits => $bits, mask => $mask);

=head1 DESCRIPTION

You can read and write a variety of images formats, assuming you have
the L<appropriate libraries|Imager::Install/EXTERNAL LIBRARIES>, and
images can be read or written to/from files, file handles, file
descriptors, scalars, or through callbacks.

To see which image formats Imager is compiled to support the following
code snippet is sufficient:

  use Imager;
  print join " ", keys %Imager::formats;

This will include some other information identifying libraries rather
than file formats.  For new code you might find the L</read_types()>
or L</write_types()> methods useful.

=over 

=item read()

Reading writing to and from files is simple, use the C<read()>
method to read an image:

  my $img = Imager->new;
  $img->read(file=>$filename, type=>$type)
    or die "Cannot read $filename: ", $img->errstr;

In most cases Imager can auto-detect the file type, so you can just
supply the file name:

  $img->read(file => $filename)
    or die "Cannot read $filename: ", $img->errstr;

The read() method accepts the C<allow_incomplete> parameter.  If this
is non-zero then read() can return true on an incomplete image and set
the C<i_incomplete> tag.

From Imager 0.68 you can supply most read() parameters to the new()
method to read the image file on creation.  If the read fails, check
Imager->errstr() for the cause:

  use Imager 0.68;
  my $img = Imager->new(file => $filename)
    or die "Cannot read $filename: ", Imager->errstr;

=item write()

and the C<write()> method to write an image:

  $img->write(file=>$filename, type=>$type)
    or die "Cannot write $filename: ", $img->errstr;

=item read_multi()

If you're reading from a format that supports multiple images per
file, use the C<read_multi()> method:

  my @imgs = Imager->read_multi(file=>$filename, type=>$type)
    or die "Cannot read $filename: ", Imager->errstr;

As with the read() method, Imager will normally detect the C<type>
automatically.

=item write_multi()

and if you want to write multiple images to a single file use the
C<write_multi()> method:

  Imager->write_multi({ file=> $filename, type=>$type }, @images)
    or die "Cannot write $filename: ", Imager->errstr;

=item read_types()

This is a class method that returns a list of the image file types
that Imager can read.

  my @types = Imager->read_types;

These types are the possible values for the C<type> parameter, not
necessarily the extension of the files you're reading.

It is possible for extra file read handlers to be loaded when
attempting to read a file, which may modify the list of available read
types.

=item write_types()

This is a class method that returns a list of the image file types
that Imager can write.

  my @types = Imager->write_types;

Note that these are the possible values for the C<type> parameter, not
necessarily the extension of the files you're writing.

It is possible for extra file write handlers to be loaded when
attempting to write a file, which may modify the list of available
write types.

=back

When writing, if the C<filename> includes an extension that Imager
recognizes, then you don't need the C<type>, but you may want to
provide one anyway.  See L</Guessing types> for information on
controlling this recognition.

The C<type> parameter is a lowercase representation of the file type,
and can be any of the following:

  bmp   Windows BitMaP (BMP)
  gif   Graphics Interchange Format (GIF)
  jpeg  JPEG/JFIF
  png   Portable Network Graphics (PNG)
  pnm   Portable aNyMap (PNM)
  raw   Raw
  sgi   SGI .rgb files
  tga   TARGA
  tiff  Tagged Image File Format (TIFF)

Support for other formats can be found on CPAN, including:
X<heif>X<QOI>X<webp>

  heif/heic   Imager::File::HEIF
  qoi         Imager::File::QOI
  webp        Imager::File::WEBP

When you read an image, Imager may set some tags, possibly including
information about the spatial resolution, textual information, and
animation information.  See L<Imager::ImageTypes/Tags> for specifics.

The open() method is a historical alias for the read() method.

=head2 Input and output

When reading or writing you can specify one of a variety of sources or
targets:

=over

=item *

C<file> - The C<file> parameter is the name of the image file to be
written to or read from.  If Imager recognizes the extension of the
file you do not need to supply a C<type>.

  # write in tiff format
  $image->write(file => "example.tif")
    or die $image->errstr;

  $image->write(file => 'foo.tmp', type => 'tiff')
    or die $image->errstr;

  my $image = Imager->new;
  $image->read(file => 'example.tif')
    or die $image->errstr;

=item *

C<fh> - C<fh> is a file handle, typically returned from an C<open>
call.  You should call C<binmode> on the handle before passing it to
Imager.

Imager will set the handle to autoflush to make sure any buffered data
is flushed , since Imager will write to the file descriptor (from
fileno()) rather than writing at the perl level.

  $image->write(fh => \*STDOUT, type => 'gif')
    or die $image->errstr;

  # for example, a file uploaded via CGI.pm
  $image->read(fd => $cgi->param('file')) 
    or die $image->errstr;

=item *

C<fd> - C<fd> is a file descriptor.  You can get this by calling the
C<fileno()> function on a file handle, or by using one of the standard
file descriptor numbers.

If you get this from a perl file handle, you may need to flush any
buffered output, otherwise it may appear in the output stream after
the image.

  $image->write(fd => file(STDOUT), type => 'gif')
    or die $image->errstr;

=item *

C<data> - When reading data, C<data> is a scalar containing the image
file data, or a reference to such a scalar.  When writing, C<data> is
a reference to the scalar to save the image file data to.

  my $data;
  $image->write(data => \$data, type => 'tiff')
    or die $image->errstr;

  my $data = $row->{someblob}; # eg. from a database
  my @images = Imager->read_multi(data => $data)
    or die Imager->errstr;

  # from Imager 0.99
  my @images = Imager->read_multi(data => \$data)
    or die Imager->errstr;

=item *

C<callback>, C<readcb>, C<writecb>, C<seekcb>, C<closecb> - Imager
will make calls back to your supplied coderefs to read, write and seek
from/to/through the image file.  See L</"I/O Callbacks"> below for details.

=item *

C<io> - an L<Imager::IO> object.

=back

X<buffering>X<unbuffered>By default Imager will use buffered I/O when
reading or writing an image.  You can disabled buffering for output by
supplying a C<< buffered => 0 >> parameter to C<write()> or
C<write_multi()>.

=head2 I/O Callbacks

When reading from a file you can use either C<callback> or C<readcb>
to supply the read callback, and when writing C<callback> or
C<writecb> to supply the write callback.

Whether reading or writing a C<TIFF> image, C<seekcb> and C<readcb>
are required.

If a file handler attempts to use C<readcb>, C<writecb> or C<seekcb>
and you haven't supplied one, the call will fail, failing the image
read or write, returning an error message indicating that the callback
is missing:

  # attempting to read a TIFF image without a seekcb
  open my $fh, "<", $filename or die;
  my $rcb = sub {
    my $val;
    read($fh, $val, $_[0]) or return "";
    return $val;
  };
  my $im = Imager->new(callback => $rcb)
    or die Imager->errstr
  # dies with (wrapped here):
  # Error opening file: (Iolayer): Failed to read directory at offset 0:
  # (Iolayer): Seek error accessing TIFF directory: seek callback called
  # but no seekcb supplied

You can also provide a C<closecb> parameter called when writing the
file is complete.  If no C<closecb> is supplied the default will
succeed silently.

  # contrived
  my $data;
  sub mywrite {
    $data .= unpack("H*", shift);
    1;
  }
  Imager->write_multi({ callback => \&mywrite, type => 'gif'}, @images)
    or die Imager->errstr;

=head3 C<readcb>

The read callback is called with 2 parameters:

=over

=item *

C<size> - the minimum amount of data required.

=item *

C<maxsize> - previously this was the maximum amount of data returnable
- currently it's always the same as C<size>

=back

Your read callback should return the data as a scalar:

=over

=item *

on success, a string containing the bytes read.

=item *

on end of file, an empty string

=item *

on error, C<undef>.

=back

If your return value contains more data than C<size> Imager will
panic.

Your return value must not contain any characters over C<\xFF> or
Imager will panic.

=head3 C<writecb>

Your write callback takes exactly one parameter, a scalar containing
the data to be written.

Return true for success.

=head3 C<seekcb>

The seek callback takes 2 parameters, a I<POSITION>, and a I<WHENCE>,
defined in the same way as perl's seek function.

Previously you always needed a C<seekcb> callback if you called
Imager's L</read()> or L</read_multi()> without a C<type> parameter,
but this is no longer necessary unless the file handler requires
seeking, such as for TIFF files.

Returns the new position in the file, or -1 on failure.

=head3 C<closecb>

You can also supply a C<closecb> which is called with no parameters
when there is no more data to be written.  This could be used to flush
buffered data.

Return true on success.

=head2 Guessing types
X<FORMATGUESS>

When writing to a file, if you don't supply a C<type> parameter Imager
will attempt to guess it from the file name.  This is done by calling
the code reference stored in C<$Imager::FORMATGUESS>.  This is only
done when write() or write_multi() is called with a C<file> parameter,
or if read() or read_multi() can't determine the type from the file's
header.

The default function value of C<$Imager::FORMATGUESS> is
C<\&Imager::def_guess_type>.

=over

=item def_guess_type()
X<methods, def_guess_type()>

This is the default function Imager uses to derive a file type from a
file name.  This is a function, not a method.

Accepts a single parameter, the file name and returns the type or
undef.

=back

You can replace function with your own implementation if you have some
specialized need.  The function takes a single parameter, the name of
the file, and should return either a file type or under.

  # I'm writing jpegs to weird filenames
  local $Imager::FORMATGUESS = sub { 'jpeg' };

When reading a file Imager examines beginning of the file for
identifying information.  The current implementation attempts to
detect the following image types beyond those supported by Imager:

=for stopwords Photoshop

=over

C<xpm>, C<mng>, C<jng>, C<ilbm>, C<pcx>, C<fits>, C<psd> (Photoshop), C<eps>, Utah
C<RLE>.

=back

You can now add to the magic database Imager uses for detecting file
types:

=over

=item add_file_magic()

  Imager->add_file_magic(name => $name, bits => $bits, mask => $mask)

Adds to list of magic, the parameters are all required.  The
parameters are:

=over

=item *

C<name> - the file type name to return on match.

=item *

C<bits> - a binary string to match.

=item *

C<mask> - a mask controlling which parts of I<bits> are significant.

=back

While I<mask> is mostly a bit mask, some byte values are translated,
the space character is treated as all zeros (C<"\x00">), and the C<x> character as
all ones (C<"\xFF">).

New magic entries take priority over old entries.

You can add more than one magic entry for a given I<name>.

  Imager->add_file_magic(name => "heif",
                         bits => "    ftypheif"
                         mask => "    xxxxxxxx");

=back

=head2 Limiting the sizes of images you read

=over

=item set_file_limits()

In some cases you will be receiving images from an untested source,
such as submissions via CGI.  To prevent such images from consuming
large amounts of memory, you can set limits on the dimensions of
images you read from files:

=over

=item *

width - limit the width in pixels of the image

=item *

height - limit the height in pixels of the image

=item *

bytes - limits the amount of storage used by the image.  This depends
on the width, height, channels and sample size of the image.  For
paletted images this is calculated as if the image was expanded to a
direct color image.

=back

To set the limits, call the class method set_file_limits:

  Imager->set_file_limits(width=>$max_width, height=>$max_height);

You can pass any or all of the limits above, any limits you do not
pass are left as they were.

Any limit of zero for width or height is treated as unlimited.

A limit of zero for bytes is treated as one gigabyte, but higher bytes
limits can be set explicitly.

By default, the width and height limits are zero, or unlimited.  The
default memory size limit is one gigabyte.

You can reset all limits to their defaults with the reset parameter:

  # no limits
  Imager->set_file_limits(reset=>1);

This can be used with the other limits to reset all but the limit you
pass:

  # only width is limited
  Imager->set_file_limits(reset=>1, width=>100);

  # only bytes is limited
  Imager->set_file_limits(reset=>1, bytes=>10_000_000);

=item get_file_limits()

You can get the current limits with the get_file_limits() method:

  my ($max_width, $max_height, $max_bytes) =
     Imager->get_file_limits();

=item check_file_limits()
X<class methods, check_file_limits()>X<check_file_limits()>

Intended for use by file handlers to check that the size of a file is
within the limits set by C<set_file_limits()>.

Parameters:

=over

=item *

C<width>, C<height> - the width and height of the image in pixels.
Must be a positive integer. Required.

=item *

C<channels> - the number of channels in the image, including the alpha
channel if any.  Must be a positive integer between 1 and 4
inclusive.  Default: 3.

=item *

C<sample_size> - the number of bytes stored per sample.  Must be a
positive integer or C<"float">.  Note that this should be the sample
size of the Imager image you will be creating, not the sample size in
the source, eg. if the source has 32-bit samples this should be
C<"float"> since Imager doesn't have 32-bit/sample images.

=back

=back

=head1 TYPE SPECIFIC INFORMATION

The different image formats can write different image type, and some have
different options to control how the images are written.

When you call C<write()> or C<write_multi()> with an option that has
the same name as a tag for the image format you're writing, then the
value supplied to that option will be used to set the corresponding
tag in the image.  Depending on the image format, these values will be
used when writing the image.

This replaces the previous options that were used when writing GIF
images.  Currently if you use an obsolete option, it will be converted
to the equivalent tag and Imager will produced a warning.  You can
suppress these warnings by calling the C<Imager::init()> function with
the C<warn_obsolete> option set to false:

  Imager::init(warn_obsolete=>0);

At some point in the future these obsolete options will no longer be
supported.

=for stopwords aNy PixMaps BitMap

=head2 PNM (Portable aNy Map)

Imager can write C<PGM> (Portable Gray Map) and C<PPM> (Portable
PixMaps) files, depending on the number of channels in the image.
Currently the images are written in binary formats.  Only 1 and 3
channel images can be written, including 1 and 3 channel paletted
images.

  $img->write(file=>'foo.ppm') or die $img->errstr;

Imager can read both the ASCII and binary versions of each of the
C<PBM> (Portable BitMap), C<PGM> and C<PPM> formats.

  $img->read(file=>'foo.ppm') or die $img->errstr;

PNM does not support the spatial resolution tags.

The following tags are set when reading a PNM file:

=over

=item *

X<pnm_maxval>C<pnm_maxval> - the C<maxvals> number from the PGM/PPM header.
Always set to 2 for a C<PBM> file.

=item *

X<pnm_type>C<pnm_type> - the type number from the C<PNM> header, 1 for ASCII
C<PBM> files, 2 for ASCII C<PGM> files, 3 for ASCII c<PPM> files, 4 for binary
C<PBM> files, 5 for binary C<PGM> files, 6 for binary C<PPM> files.

=back

The following tag is checked when writing an image with more than
8-bits/sample:

=over

=item *

X<pnm_write_wide_data>pnm_write_wide_data - if this is non-zero then
write() can write C<PGM>/C<PPM> files with 16-bits/sample.  Some
applications, for example GIMP 2.2, and tools can only read
8-bit/sample binary PNM files, so Imager will only write a 16-bit
image when this tag is non-zero.

=back

=head2 JPEG

You can supply a C<jpegquality> parameter ranging from 0 (worst
quality) to 100 (best quality) when writing a JPEG file, which
defaults to 75.

  $img->write(file=>'foo.jpg', jpegquality=>90) or die $img->errstr;

If you write an image with an alpha channel to a JPEG file then it
will be composed against the background set by the C<i_background>
parameter (or tag), or black if not supplied.

Imager will read a gray scale JPEG as a 1 channel image and a color
JPEG as a 3 channel image.

  $img->read(file=>'foo.jpg') or die $img->errstr;

The following tags are set in a JPEG image when read, and can be set
to control output:

=over

=item *

C<jpeg_density_unit> - The value of the density unit field in the
C<JFIF> header.  This is ignored on writing if the C<i_aspect_only>
tag is non-zero.

The C<i_xres> and C<i_yres> tags are expressed in pixels per inch no
matter the value of this tag, they will be converted to/from the value
stored in the JPEG file.

=item *

C<jpeg_density_unit_name> - This is set when reading a JPEG file to
the name of the unit given by C<jpeg_density_unit>.  Possible results
include C<inch>, C<centimeter>, C<none> (the C<i_aspect_only> tag is
also set reading these files).  If the value of C<jpeg_density_unit>
is unknown then this tag isn't set.

=item *

C<jpeg_comment> - Text comment.

=item *

C<jpeg_progressive> - Whether the JPEG file is a progressive
file. (Imager 0.84)

=back

JPEG supports the spatial resolution tags C<i_xres>, C<i_yres> and
C<i_aspect_only>.

You can also set the following tags when writing to an image, they are
not set in the image when reading:

=over

=item *

C<jpeg_optimize> - set to a non-zero integer to compute optimal
Huffman coding tables for the image.  This will increase memory usage
and processing time (about 12% in my simple tests) but can
significantly reduce file size without a loss of quality.

=item *

C<jpeg_compress_profile> - set to either C<fastest>, the default, or
only with C<MozJPEG>, to C<max>.  Setting this to any other value will
cause an error, failing the write() call.  Setting this to C<max>
without C<MozJPEG> will cause an error.

  use Imager::File::JPEG;
  my $prof = Imager::File::JPEG->is_mozjpeg ? "max" : "fastest";
  $im->write(file => "foo.jpeg", jpeg_compress_profile => $prof)
     or die $im->errstr;

Note that unlike C<MozJPEG>, Imager always defaults to C<fastest>.

=item *

C<jpeg_tune> - corresponds to the C<MozJPEG> C<cjpeg> C<-tune>
parameters, this can be any of:

=over

=item * C<psnr>

=item * C<ssim>

=item * C<ms-ssim>

=item * C<hvs-psnr>

=back

These set the same values as the C<jpeg_base_quant_tbl_idx>,
C<jpeg_lambda_log_scale1>, C<jpeg_lambda_log_scale2> and
C<jpeg_use_lambda_weight_tbl> tags, which can override the values set
by C<jpeg_tune>.

Unlike C<cjpeg> C<-tune>, C<jpeg_tune> doesn't force the quality to
75.

Requires that Imager::File::JPEG was built with C<MozJPEG>.

=item *

C<jpeg_arithmetic> - if set to non-zero, use arithmetic coding when
writing the image.  This requires that the C<libjpeg> variant that
L<Imager::File::JPEG> was built with had encode support for arithmetic
coding enabled when it was built.

=item *

=for stopwords JFIF

C<jpeg_jfif> - if set to zero, disable writing the JFIF header even if
one is technically required, which it is for the color spaces Imager
works with.  This saves 18 bytes in the output file and most
applications including web browsers will successfully read the file,
but your experience may differ.

This will prevent the C<i_xres>, C<i_yres> and C<jpeg_density_units>
tags from having an effect.

=item *

C<jpeg_smooth> - if set to a value from 1 to 100 apply smoothing to
the image to eliminate dithering noise (without modifying the Imager
image).  Default: 0 (no smoothing).

=item *

=for stopwords MCUs

C<jpeg_restart> - if set to a plain integer C<N>, generate a JPEG
restart marker every C<N> rows, if set to an integer followed by C<B>,
generate a JPEG restart marker every C<N> MCUs, the 8x8 pixel blocks
that make up a JPEG image.  Note that if this is specified in rows it
will be translated to MCUs by C<libjpeg>.

This allows a decoder to recover from corruption, but it makes the
file slightly larger.

Default: 0, no restart markers are produced.

=item *

=for stopwords subsampling YCbCr

C<jpeg_sample> - control subsampling of the YCbCr components,
equivalent to the C<-sample> parameter for C<cjpeg>.

Default: "2x2,1x1,1x1", default 4:2:0 JPEG subsampling.

=back

The following options can be set on writing with C<MozJPEG> and
correspond directly to the API options described in the C<MozJPEG>
F<README-mozilla.txt>.  Attempting to set them when Imager::File::JPEG
has been built with another C<libjpeg> will result in an error.

=over

=item *

C<jpeg_optimize_scans>, C<jpeg_trellis_quant>,
C<jpeg_trellis_quant_dc>, C<jpeg_tresllis_eob_opt>,
C<jpeg_use_lambda_weight_tbl>, C<jpeg_use_scans_in_trellis>,
C<jpeg_overshoot_deringing> - boolean options, set to 0 or 1.

C<jpeg_lambda_log_scale1>, C<jpeg_lambda_log_scale2>,
C<jpeg_trellis_delta_dc_weight> - integer options.


C<jpeg_trellis_freq_split>, C<jpeg_trellis_num_loops>,
C<jpeg_base_quant_tbl_idx>, C<jpeg_dc_scan_opt_mode> - floating point
options.

=back

When reading a JPEG image, the following tag will be set, and ignored
on writing:

=over

=item *

C<jpeg_read_arithmetic> - the image had been written with arithmetic
coding.  This uses a separate name from writing to avoid arithmetic
coding from being accidentally propagated to a file that might need
to be read by an implementation without arithmetic coding support.

=back

=for stopwords EXIF

If an C<APP1> block containing EXIF information is found, then any of the
following tags can be set when reading a JPEG image:

=over

exif_aperture exif_artist exif_brightness exif_color_space
exif_contrast exif_copyright exif_custom_rendered exif_date_time
exif_date_time_digitized exif_date_time_original
exif_digital_zoom_ratio exif_exposure_bias exif_exposure_index
exif_exposure_mode exif_exposure_program exif_exposure_time
exif_f_number exif_flash exif_flash_energy exif_flashpix_version
exif_focal_length exif_focal_length_in_35mm_film
exif_focal_plane_resolution_unit exif_focal_plane_x_resolution
exif_focal_plane_y_resolution exif_gain_control exif_image_description
exif_image_unique_id exif_iso_speed_rating exif_make exif_max_aperture
exif_metering_mode exif_model exif_orientation exif_related_sound_file
exif_resolution_unit exif_saturation exif_scene_capture_type
exif_sensing_method exif_sharpness exif_shutter_speed exif_software
exif_spectral_sensitivity exif_sub_sec_time
exif_sub_sec_time_digitized exif_sub_sec_time_original
exif_subject_distance exif_subject_distance_range
exif_subject_location exif_tag_light_source exif_user_comment
exif_version exif_white_balance exif_x_resolution exif_y_resolution

=back

The following derived tags can also be set when reading a JPEG image:

=over

exif_color_space_name exif_contrast_name exif_custom_rendered_name
exif_exposure_mode_name exif_exposure_program_name exif_flash_name
exif_focal_plane_resolution_unit_name exif_gain_control_name
exif_light_source_name exif_metering_mode_name
exif_resolution_unit_name exif_saturation_name
exif_scene_capture_type_name exif_sensing_method_name
exif_sharpness_name exif_subject_distance_range_name
exif_white_balance_name

=back

The derived tags are for enumerated fields, when the value for the
base field is valid then the text that appears in the EXIF
specification for that value appears in the derived field.  So for
example if C<exf_metering_mode> is C<5> then
C<exif_metering_mode_name> is set to C<Pattern>.

eg.

  my $image = Imager->new;
  $image->read(file => 'exiftest.jpg')
    or die "Cannot load image: ", $image->errstr;
  print $image->tags(name => "exif_image_description"), "\n";
  print $image->tags(name => "exif_exposure_mode"), "\n";
  print $image->tags(name => "exif_exposure_mode_name"), "\n";

  # for the exiftest.jpg in the Imager distribution the output would be:
  Imager Development Notes
  0
  Auto exposure

Imager will not write EXIF tags to any type of image, if you need more
advanced EXIF handling, consider L<Image::ExifTool>.

=for stopwords IPTC

=over

=item parseiptc()

Historically, Imager saves IPTC data when reading a JPEG image, the
parseiptc() method returns a list of key/value pairs resulting from a
simple decoding of that data.

Any future IPTC data decoding is likely to go into tags.

=back

=head2 GIF

When writing one of more GIF images you can use the same
L<Quantization Options|Imager::ImageTypes> as you can when converting
an RGB image into a paletted image.

When reading a GIF all of the sub-images are combined using the screen
size and image positions into one big image, producing an RGB image.
This may change in the future to produce a paletted image where possible.

When you read a single GIF with C<$img-E<gt>read()> you can supply a
reference to a scalar in the C<colors> parameter, if the image is read
the scalar will be filled with a reference to an anonymous array of
L<Imager::Color> objects, representing the palette of the image.  This
will be the first palette found in the image.  If you want the
palettes for each of the images in the file, use C<read_multi()> and
use the C<getcolors()> method on each image.

GIF does not support the spatial resolution tags.

Imager will set the following tags in each image when reading, and can
use most of them when writing to GIF:

=over

=item *

gif_left - the offset of the image from the left of the "screen"
("Image Left Position")

=item *

gif_top - the offset of the image from the top of the "screen" ("Image
Top Position")

=item *

gif_interlace - non-zero if the image was interlaced ("Interlace
Flag")

=item *

gif_screen_width, gif_screen_height - the size of the logical
screen. When writing this is used as the minimum.  If any image being
written would extend beyond this then the screen size is extended.
("Logical Screen Width", "Logical Screen Height").

=item *

gif_local_map - Non-zero if this image had a local color map.  If set
for an image when writing the image is quantized separately from the
other images in the file.

=item *

gif_background - The index in the global color map of the logical
screen's background color.  This is only set if the current image uses
the global color map.  You can set this on write too, but for it to
choose the color you want, you will need to supply only paletted
images and set the C<gif_eliminate_unused> tag to 0.

=item *

gif_trans_index - The index of the color in the color map used for
transparency.  If the image has a transparency then it is returned as
a 4 channel image with the alpha set to zero in this palette entry.
This value is not used when writing. ("Transparent Color Index")

=item *

gif_trans_color - A reference to an Imager::Color object, which is the
color to use for the palette entry used to represent transparency in
the palette.  You need to set the C<transp> option (see
L<Imager::ImageTypes/"Quantization options">) for this value to be
used.

=item *

gif_delay - The delay until the next frame is displayed, in 1/100 of a
second.  ("Delay Time").

=item *

gif_user_input - whether or not a user input is expected before
continuing (view dependent) ("User Input Flag").

=item *

gif_disposal - how the next frame is displayed ("Disposal Method")

=item *

gif_loop - the number of loops from the Netscape Loop extension.  This
may be zero to loop forever.

=item *

gif_comment - the first block of the first GIF comment before each
image.

=item *

gif_eliminate_unused - If this is true, when you write a paletted
image any unused colors will be eliminated from its palette.  This is
set by default.

=item *

gif_colormap_size - the original size of the color map for the image.
The color map of the image may have been expanded to include out of
range color indexes.

=back

Where applicable, the ("name") is the name of that field from the C<GIF89>
standard.

The following GIF writing options are obsolete, you should set the
corresponding tag in the image, either by using the tags functions, or
by supplying the tag and value as options.

=over

=item *

gif_each_palette - Each image in the GIF file has it's own palette if
this is non-zero.  All but the first image has a local color table
(the first uses the global color table.

Use C<gif_local_map> in new code.

=item *

interlace - The images are written interlaced if this is non-zero.

Use C<gif_interlace> in new code.

=item *

gif_delays - A reference to an array containing the delays between
images, in 1/100 seconds.

Use C<gif_delay> in new code.

=item *

gif_positions - A reference to an array of references to arrays which
represent screen positions for each image.

New code should use the C<gif_left> and C<gif_top> tags.

=item *

gif_loop_count - If this is non-zero the Netscape loop extension block
is generated, which makes the animation of the images repeat.

This is currently unimplemented due to some limitations in C<giflib>.

=back

You can supply a C<page> parameter to the C<read()> method to read
some page other than the first.  The page is 0 based:

  # read the second image in the file
  $image->read(file=>"example.gif", page=>1)
    or die "Cannot read second page: ",$image->errstr,"\n";

Before release 0.46, Imager would read multiple image GIF image files
into a single image, overlaying each of the images onto the virtual
GIF screen.

As of 0.46 the default is to read the first image from the file, as if
called with C<< page => 0 >>.

You can return to the previous behavior by calling read with the
C<gif_consolidate> parameter set to a true value:

  $img->read(file=>$some_gif_file, gif_consolidate=>1);

As with the to_paletted() method, if you supply a colors parameter as
a reference to an array, this will be filled with Imager::Color
objects of the color table generated for the image file.

=head2 TIFF (Tagged Image File Format)

Imager can write images to either paletted or RGB TIFF images,
depending on the type of the source image.

When writing direct color images to TIFF the sample size of the
output file depends on the input:

=over

=item *

double/sample - written as 32-bit/sample TIFF

=item *

16-bit/sample - written as 16-bit/sample TIFF

=item *

8-bit/sample - written as 8-bit/sample TIFF

=back

For paletted images:

=over

=item *

C<< $img->is_bilevel >> is true - the image is written as bi-level

=item *

otherwise - image is written as paletted.

=back

If you are creating images for faxing you can set the I<class>
parameter set to C<fax>.  By default the image is written in fine
mode, but this can be overridden by setting the I<fax_fine> parameter
to zero.  Since a fax image is bi-level, Imager uses a threshold to
decide if a given pixel is black or white, based on a single channel.
For gray scale images channel 0 is used, for color images channel 1
(green) is used.  If you want more control over the conversion you can
use $img->to_paletted() to product a bi-level image.  This way you can
use dithering:

  my $bilevel = $img->to_paletted(make_colors => 'mono',
                                  translate => 'errdiff',
                                  errdiff => 'stucki');

=over

=item *

C<class> - If set to 'fax' the image will be written as a bi-level fax
image.

=item *

C<fax_fine> - By default when C<class> is set to 'fax' the image is
written in fine mode, you can select normal mode by setting
C<fax_fine> to 0.

=back

Imager should be able to read any TIFF image you supply.  Paletted
TIFF images are read as paletted Imager images, since paletted TIFF
images have 16-bits/sample (48-bits/color) this means the bottom
8-bits are lost, but this shouldn't be a big deal.

TIFF supports the spatial resolution tags.  See the
C<tiff_resolutionunit> tag for some extra options.

As of Imager 0.62 Imager reads:

=over

=item *

8-bit/sample gray, RGB or CMYK images, including a possible alpha
channel as an 8-bit/sample image.

=item *

16-bit gray, RGB, or CMYK image, including a possible alpha channel as
a 16-bit/sample image.

=item *

32-bit gray, RGB image, including a possible alpha channel as a
double/sample image.

=item *

bi-level images as paletted images containing only black and white,
which other formats will also write as bi-level.

=item *

tiled paletted images are now handled correctly

=item *

other images are read using C<tifflib>'s RGBA interface as
8-bit/sample images.

=back

The following tags are set in a TIFF image when read, and can be set
to control output:

=over

=item *

C<tiff_compression> - When reading an image this is set to the numeric
value of the TIFF compression tag.

On writing you can set this to either a numeric compression tag value,
or one of the following values:

  Ident     Number  Description
  none         1    No compression
  packbits   32773  Macintosh RLE
  ccittrle     2    CCITT RLE
  fax3         3    CCITT Group 3 fax encoding (T.4)
  t4           3    As above
  fax4         4    CCITT Group 4 fax encoding (T.6)
  t6           4    As above
  lzw          5    LZW
  jpeg         7    JPEG
  zip          8    Deflate (GZIP) Non-standard
  deflate      8    As above.
  oldzip     32946  Deflate with an older code.
  ccittrlew  32771  Word aligned CCITT RLE

In general a compression setting will be ignored where it doesn't make
sense, eg. C<jpeg> will be ignored for compression if the image is
being written as bilevel.

=for stopwords LZW

Imager attempts to check that your build of C<libtiff> supports the
given compression, and will fallback to C<packbits> if it isn't
enabled.  eg. older distributions didn't include LZW compression, and
JPEG compression is only available if C<libtiff> is configured with
C<libjpeg>'s location.

  $im->write(file => 'foo.tif', tiff_compression => 'lzw')
    or die $im->errstr;

=item *

C<tags, tiff_jpegquality>C<tiff_jpegquality> - If C<tiff_compression>
is C<jpeg> then this can be a number from 1 to 100 giving the JPEG
compression quality.  High values are better quality and larger files.

=item *

X<tags, tiff_resolutionunit>C<tiff_resolutionunit> - The value of the
C<ResolutionUnit> tag.  This is ignored on writing if the
i_aspect_only tag is non-zero.

The C<i_xres> and C<i_yres> tags are expressed in pixels per inch no
matter the value of this tag, they will be converted to/from the value
stored in the TIFF file.

=item *

X<tags, tiff_resolutionunit_name>C<tiff_resolutionunit_name> - This is
set when reading a TIFF file to the name of the unit given by
C<tiff_resolutionunit>.  Possible results include C<inch>,
C<centimeter>, C<none> (the C<i_aspect_only> tag is also set reading
these files) or C<unknown>.

=item *

X<tags, tiff_bitspersample>C<tiff_bitspersample> - Bits per sample
from the image.  This value is not used when writing an image, it is
only set on a read image.

=item *

X<tags, tiff_photometric>C<tiff_photometric> - Value of the
C<PhotometricInterpretation> tag from the image.  This value is not
used when writing an image, it is only set on a read image.

=item *

C<tiff_documentname>, C<tiff_imagedescription>, C<tiff_make>,
C<tiff_model>, C<tiff_pagename>, C<tiff_software>, C<tiff_datetime>,
C<tiff_artist>, C<tiff_hostcomputer> - Various strings describing the
image.  C<tiff_datetime> must be formatted as "YYYY:MM:DD HH:MM:SS".
These correspond directly to the mixed case names in the TIFF
specification.  These are set in images read from a TIFF and saved
when writing a TIFF image.

=back

You can supply a C<page> parameter to the C<read()> method to read
some page other than the first.  The page is 0 based:

  # read the second image in the file
  $image->read(file=>"example.tif", page=>1)
    or die "Cannot read second page: ",$image->errstr,"\n";

If you read an image with multiple alpha channels, then only the first
alpha channel will be read.

When reading a C<TIFF> image with callbacks, the C<seekcb> callback
parameter is also required.

When writing a C<TIFF> image with callbacks, the C<seekcb> and
C<readcb> parameters are also required.

C<TIFF> is a random access file format, it cannot be read from or
written to unseekable streams such as pipes or sockets.

=head2 BMP (Windows Bitmap)

Imager can write 24-bit RGB, and 8, 4 and 1-bit per pixel paletted
Windows BMP files.  Currently you cannot write compressed BMP files
with Imager.

Imager can read 24-bit RGB, and 8, 4 and 1-bit perl pixel paletted
Windows BMP files.  There is some support for reading 16-bit per pixel
images, but I haven't found any for testing.

BMP has no support for multiple image files.

BMP files support the spatial resolution tags, but since BMP has no
support for storing only an aspect ratio, if C<i_aspect_only> is set
when you write the C<i_xres> and C<i_yres> values are scaled so the
smaller is 72 DPI.

The following tags are set when you read an image from a BMP file:

=over

=item bmp_compression

The type of compression, if any.  This can be any of the following
values:

=for stopwords RLE

=over

=item BI_RGB (0)

Uncompressed.

=item BI_RLE8 (1)

8-bits/pixel paletted value RLE compression.

=item BI_RLE4 (2)

4-bits/pixel paletted value RLE compression.

=item BI_BITFIELDS (3)

Packed RGB values.

=back

=item bmp_compression_name

The bmp_compression value as a BI_* string

=item bmp_important_colors

The number of important colors as defined by the writer of the image.

=item bmp_used_colors

Number of color used from the BMP header

=item bmp_filesize

The file size from the BMP header

=item bmp_bit_count

Number of bits stored per pixel. (24, 8, 4 or 1)

=back

=for stopwords Targa

=head2 TGA (Targa)

When storing Targa images RLE compression can be activated with the
C<compress> parameter, the C<idstring> parameter can be used to set the
Targa comment field and the C<wierdpack> option can be used to use the
15 and 16 bit Targa formats for RGB and RGBA data.  The 15 bit format
has 5 of each red, green and blue.  The 16 bit format in addition
allows 1 bit of alpha.  The most significant bits are used for each
channel.

Tags:

=over

=item tga_idstring

=item tga_bitspp

=item compressed

=back

=head2 RAW

When reading raw images you need to supply the width and height of the
image in the C<xsize> and C<ysize> options:

  $img->read(file=>'foo.raw', xsize=>100, ysize=>100)
    or die "Cannot read raw image\n";

If your input file has more channels than you want, or (as is common),
junk in the fourth channel, you can use the C<raw_datachannels> and
C<raw_storechannels> options to control the number of channels in your input
file and the resulting channels in your image.  For example, if your
input image uses 32-bits per pixel with red, green, blue and junk
values for each pixel you could do:

  $img->read(file=>'foo.raw', xsize => 100, ysize => 100,
             raw_datachannels => 4, raw_storechannels => 3,
	     raw_interleave => 0)
    or die "Cannot read raw image\n";

In general, if you supply C<raw_storechannels> you should also supply
C<raw_datachannels>

Read parameters:

=over

=item *

C<raw_interleave> - controls the ordering of samples within the image.
Default: 1.  Alternatively and historically spelled C<interleave>.
Possible values:

=over

=item *

0 - samples are pixel by pixel, so all samples for the first pixel,
then all samples for the second pixel and so on.  eg. for a four pixel
scan line the channels would be laid out as:

  012012012012

=item *

1 - samples are line by line, so channel 0 for the entire scan line is
followed by channel 1 for the entire scan line and so on.  eg. for a
four pixel scan line the channels would be laid out as:

  000011112222

This is the default.

=back

Unfortunately, historically, the default C<raw_interleave> for read
has been 1, while writing only supports the C<raw_interleave> = 0
format.

For future compatibility, you should always supply the
C<raw_interleave> (or C<interleave>) parameter.  As of 0.68, Imager
will warn if you attempt to read a raw image without a
C<raw_interleave> parameter.

=item *

C<raw_storechannels> - the number of channels to store in the image.
Range: 1 to 4.  Default: 3.  Alternatively and historically spelled
C<storechannels>.

=item *

C<raw_datachannels> - the number of channels to read from the file.
Range: 1 or more.  Default: 3.  Alternatively and historically spelled
C<datachannels>.

=back

  $img->read(file=>'foo.raw', xsize=100, ysize=>100, raw_interleave=>1)
    or die "Cannot read raw image\n";

=head2 PNG

=head3 PNG Image modes

PNG files can be read and written in the following modes:

=over

=item *

bi-level - written as a 1-bit per sample gray scale image

=item *

paletted - Imager gray scale paletted images are written as RGB
paletted images.  PNG palettes can include alpha values for each entry
and this is honored as an Imager four channel paletted image.

=item *

8 and 16-bit per sample gray scale, optionally with an alpha channel.

=item *

8 and 16-bit per sample RGB, optionally with an alpha channel.

=back

Unlike GIF, there is no automatic conversion to a paletted image,
since PNG supports direct color.

=head3 PNG Text tags

Text tags are retrieved from and written to PNG C<tEXT> or C<zTXT>
chunks.  The following standard tags from the PNG specification are
directly supported:

=over

=item *

C<i_comment>X<tags,i_comment> - keyword of "Comment".

=item *

C<png_author>X<tags,PNG,png_author> - keyword "Author".

=item *

C<png_copyright>X<tags,PNG,png_copyright> - keyword "Copyright".

=item *

C<png_creation_time>X<tags,PNG,png_creation_time> - keyword "Creation Time".

=item *

C<png_description>X<tags,PNG,png_description> - keyword "Description".

=item *

C<png_disclaimer>X<tags,PNG,png_disclaimer> - keyword "Disclaimer".

=item *

C<png_software>X<tags,PNG,png_software> - keyword "Software".

=item *

C<png_title>X<tags,PNG,png_title> - keyword "Title".

=item *

C<png_warning>X<tags,PNG,png_warning> - keyword "Warning".

=back

Each of these tags has a corresponding C<< I<base-tag-name>_compressed
>> tag, eg. C<png_comment_compressed>.  When reading, if the PNG chunk
is compressed this tag will be set to 1, but is otherwise unset.  When
writing, Imager will honor the compression tag if set and non-zero,
otherwise the chunk text will be compressed if the value is longer
than 1000 characters, as recommended by the C<libpng> documentation.

PNG C<tEXT> or C<zTXT> chunks outside of those above are read into or
written from Imager tags named like:

=over

=item *

C<< png_textI<N>_key >> - the key for the text chunk.  This can be 1
to 79 characters, may not contain any leading, trailing or consecutive
spaces, and may contain only Latin-1 characters from 32-126, 161-255.

=item *

C<< png_textI<N>_text >> - the text for the text chunk.  This may not
contain any C<NUL> characters.

=item *

C<< png_textI<N>_compressed >> - whether or not the text chunk is
compressed.  This behaves similarly to the C<<
I<base-tag-name>_compressed >> tags described above.

=back

Where I<N> starts from 0.  When writing both the C<..._key> and
C<..._text> tags must be present or the write will fail.  If the key
or text do not satisfy the requirements above the write will fail.

=head3 Other PNG metadata tags

=over

=item *

X<tags, png_interlace>C<png_interlace>, C<png_interlace_name> - only
set when reading, C<png_interlace> is set to the type of interlacing
used by the file, 0 for one, 1 for Adam7.  C<png_interlace_name> is
set to a keyword describing the interlacing, either C<none> or
C<adam7>.

=item *

X<tags, png_srgb_intent>C<png_srgb_intent> - the sRGB rendering intent
for the image. an integer from 0 to 3, per the PNG specification.  If
this chunk is found in the PNG file the C<gAMA> and C<cHRM> are
ignored and the C<png_gamma> and C<png_chroma_...> tags are not set.
Similarly when writing if C<png_srgb_intent> is set the C<gAMA> and
C<cHRM> chunks are not written.

=item *

X<tags, png_gamma>C<png_gamma> - the gamma of the image. This value is
not currently used by Imager when processing the image, but this may
change in the future.

=item *

X<tags, png_chroma_...>C<png_chroma_white_x>, C<png_chroma_white_y>,
C<png_chroma_red_x>, C<png_chroma_red_y>, C<png_chroma_green_x>,
C<png_chroma_green_y>, C<png_chroma_blue_x>, C<png_chroma_blue_y> -
the primary chromaticities of the image, defining the color model.
This is currently not used by Imager when processing the image, but
this may change in the future.

=item *

C<i_xres>, C<i_yres>, C<i_aspect_only> - processed per
I<Imager::ImageTypes/CommonTags>.

=item *

X<tags, png_bits>C<png_bits> - the number of bits per sample in the
representation.  Ignored when writing.

=item *

X<tags, png_time>C<png_time> - the creation time of the file formatted
as C<< I<year>-I<month>-I<day>TI<hour>:I<minute>:I<second> >>.  This
is stored as time data structure in the file, not a string.  If you
set C<png_time> and it cannot be parsed as above, writing the PNG file
will fail.

=item *

C<i_background> - set from the C<sBKG> when reading an image file.

=back

X<compression>X<png_compression_level>You can control the level of
F<zlib> compression used when writing with the
C<png_compression_level> parameter.  This can be an integer between 0
(uncompressed) and 9 (best compression).

=for stopwords
CRC

X<png_ignore_benign_errors>If you're using F<libpng> 1.6 or later, or
an earlier release configured with C<PNG_BENIGN_ERRORS_SUPPORTED>, you
can choose to ignore file format errors the authors of F<libpng>
consider I<benign>, this includes at least CRC errors and palette
index overflows.  Do this by supplying a true value for the
C<png_ignore_benign_errors> parameter to the read() method:

  $im->read(file => "foo.png", png_ignore_benign_errors => 1)
    or die $im->errstr;

=head2 ICO (Microsoft Windows Icon) and CUR (Microsoft Windows Cursor)

Icon and Cursor files are very similar, the only differences being a
number in the header and the storage of the cursor hot spot.  I've
treated them separately so that you're not messing with tags to
distinguish between them.

The following tags are set when reading an icon image and are used
when writing it:

=over

=item ico_mask

This is the AND mask of the icon.  When used as an icon in Windows 1
bits in the mask correspond to pixels that are modified by the source
image rather than simply replaced by the source image.

Rather than requiring a binary bitmap this is accepted in a specific format:

=over

=item *

first line consisting of the 0 placeholder, the 1 placeholder and a
newline.

=item *

following lines which contain 0 and 1 placeholders for each scan line
of the image, starting from the top of the image.

=back

When reading an image, '.' is used as the 0 placeholder and '*' as the
1 placeholder.  An example:

  .*
  ..........................******
  ..........................******
  ..........................******
  ..........................******
  ...........................*****
  ............................****
  ............................****
  .............................***
  .............................***
  .............................***
  .............................***
  ..............................**
  ..............................**
  ...............................*
  ...............................*
  ................................
  ................................
  ................................
  ................................
  ................................
  ................................
  *...............................
  **..............................
  **..............................
  ***.............................
  ***.............................
  ****............................
  ****............................
  *****...........................
  *****...........................
  *****...........................
  *****...........................

=back

The following tags are set when reading an icon:

=over

=item ico_bits

The number of bits per pixel used to store the image.

=back

For cursor files the following tags are set and read when reading and
writing:

=over

=item cur_mask

This is the same as the ico_mask above.

=item cur_hotspotx

=item cur_hotspoty

The "hot" spot of the cursor image.  This is the spot on the cursor
that you click with.  If you set these to out of range values they are
clipped to the size of the image when written to the file.

=back

The following parameters can be supplied to read() or read_multi() to
control reading of ICO/CUR files:

=over

=item *

C<ico_masked> - if true, the default, then the icon/cursors mask is
applied as an alpha channel to the image, unless that image already
has an alpha channel.  This may result in a paletted image being
returned as a direct color image.  Default: 1

  # retrieve the image as stored, without using the mask as an alpha
  # channel
  $img->read(file => 'foo.ico', ico_masked => 0)
    or die $img->errstr;

This was introduced in Imager 0.60.  Previously reading ICO images
acted as if C<ico_masked =E<gt> 0>.

=item *

C<ico_alpha_masked> - if true, then the icon/cursor mask is applied as
an alpha channel to images that already have an alpha mask.  Note that
this will only make pixels transparent, not opaque.  Default: 0.

Note: If you get different results between C<ico_alpha_masked> being
set to 0 and 1, your mask may break when used with the Win32 API.

=back

C<cur_bits> is set when reading a cursor.

Examples:

  my $img = Imager->new(xsize => 32, ysize => 32, channels => 4);
  $im->box(color => 'FF0000');
  $im->write(file => 'box.ico');

  $im->settag(name => 'cur_hotspotx', value => 16);
  $im->settag(name => 'cur_hotspoty', value => 16);
  $im->write(file => 'box.cur');

=for stopwords BW

=head2 SGI (RGB, BW)

SGI images, often called by the extensions, RGB or BW, can be stored
either uncompressed or compressed using an RLE compression.

By default, when saving to an extension of C<rgb>, C<bw>, C<sgi>,
C<rgba> the file will be saved in SGI format.  The file extension is
otherwise ignored, so saving a 3-channel image to a C<.bw> file will
result in a 3-channel image on disk.

The following tags are set when reading a SGI image:

=over

=item *

i_comment - the C<IMAGENAME> field from the image.  Also written to
the file when writing.

=item *

sgi_pixmin, sgi_pixmax - the C<PIXMIN> and C<PIXMAX> fields from the
image.  On reading image data is expanded from this range to the full
range of samples in the image.

=item *

sgi_bpc - the number of bytes per sample for the image.  Ignored when
writing.

=item *

sgi_rle - whether or not the image is compressed.  If this is non-zero
when writing the image will be compressed.

=back

=head1 ADDING NEW FORMATS

To support a new format for reading, call the register_reader() class
method:

=over

=item register_reader()

Registers single or multiple image read functions.

Parameters:

=over

=item *

type - the identifier of the file format, if Imager's
i_test_format_probe() can identify the format then this value should
match i_test_format_probe()'s result.

This parameter is required.

=item *

single - a code ref to read a single image from a file.  This is
supplied:

=over

=item *

the object that read() was called on,

=item *

an Imager::IO object that should be used to read the file, and

=item *

all the parameters supplied to the read() method.

=back

The single parameter is required.

=item *

multiple - a code ref which is called to read multiple images from a
file. This is supplied:

=over

=item *

an Imager::IO object that should be used to read the file, and

=item *

all the parameters supplied to the read_multi() method.

=back

=back

Example:

  # from Imager::File::ICO
  Imager->register_reader
    (
     type=>'ico',
     single => 
     sub { 
       my ($im, $io, %hsh) = @_;
       $im->{IMG} = i_readico_single($io, $hsh{page} || 0);

       unless ($im->{IMG}) {
         $im->_set_error(Imager->_error_as_msg);
         return;
       }
       return $im;
     },
     multiple =>
     sub {
       my ($io, %hsh) = @_;
     
       my @imgs = i_readico_multi($io);
       unless (@imgs) {
         Imager->_set_error(Imager->_error_as_msg);
         return;
       }
       return map { 
         bless { IMG => $_, DEBUG => $Imager::DEBUG, ERRSTR => undef }, 'Imager'
       } @imgs;
     },
    );

=item register_writer()

Registers single or multiple image write functions.

Parameters:

=over

=item *

type - the identifier of the file format.  This is typically the
extension in lowercase.

This parameter is required.

=item *

single - a code ref to write a single image to a file.  This is
supplied:

=over

=item *

the object that write() was called on,

=item *

an Imager::IO object that should be used to write the file, and

=item *

all the parameters supplied to the write() method.

=back

The single parameter is required.

=item *

multiple - a code ref which is called to write multiple images to a
file. This is supplied:

=over

=item *

the class name write_multi() was called on, this is typically
C<Imager>.

=item *

an Imager::IO object that should be used to write the file, and

=item *

all the parameters supplied to the read_multi() method.

=back

=back

=item add_type_extensions($type, $ext, ...)

This class method can be used to add extensions to the map used by
C<def_guess_type> when working out the file type a filename extension.

  Imager->add_type_extension(mytype => "mytype", "mytypish");
  ...
  $im->write(file => "foo.mytypish") # use the mytype handler

=back

If you name the reader module C<Imager::File::>I<your-format-name>
where I<your-format-name> is a fully upper case version of the type
value you would pass to read(), read_multi(), write() or write_multi()
then Imager will attempt to load that module if it has no other way to
read or write that format.

For example, if you create a module Imager::File::GIF and the user has
built Imager without it's normal GIF support then an attempt to read a
GIF image will attempt to load Imager::File::GIF.

If your module can only handle reading then you can name your module
C<Imager::File::>I<your-format-name>C<Reader> and Imager will attempt
to autoload it.

If your module can only handle writing then you can name your module 
C<Imager::File::>I<your-format-name>C<Writer> and Imager will attempt
to autoload it.

=head1 PRELOADING FILE MODULES

=over

=item preload()

C<Imager->preload> preloads the file support modules included with or
that have been included with Imager in the past.

It isn't typically needed, but some cases where you might want to use
it:

=over

=item *

For use in forking servers such as mod_perl to allow as many pages as
possible to be shared between parent and child processes.

=item *

to avoid runtime loading of a module from delaying output in an
animation.

=item *

if you're loading modules from a relative C<$ENV{PERL5LIB}> and expect
to change directories.

=back

You probably don't need it.

If the module is not available no error occurs.

Preserves $@.

  use Imager;
  Imager->preload;

=back

=head1 EXAMPLES

=head2 Producing an image from a CGI script

Once you have an image the basic mechanism is:

=for stopwords STDOUT

=over

=item 1.

set STDOUT to autoflush

=item 2.

output a content-type header, and optionally a content-length header

=item 3.

put STDOUT into binmode

=item 4.

call write() with the C<fd> or C<fh> parameter.  You will need to
provide the C<type> parameter since Imager can't use the extension to
guess the file format you want.

=back

  # write an image from a CGI script
  # using CGI.pm
  use CGI qw(:standard);
  $| = 1;
  binmode STDOUT;
  print header(-type=>'image/gif');
  $img->write(type=>'gif', fd=>fileno(STDOUT))
    or die $img->errstr;

If you want to send a content length you can send the output to a
scalar to get the length:

  my $data;
  $img->write(type=>'gif', data=>\$data)
    or die $img->errstr;
  binmode STDOUT;
  print header(-type=>'image/gif', -content_length=>length($data));
  print $data;

=head2 Writing an animated GIF

The basic idea is simple, just use write_multi():

  my @imgs = ...;
  Imager->write_multi({ file=>$filename, type=>'gif' }, @imgs);

If your images are RGB images the default quantization mechanism will
produce a very good result, but can take a long time to execute.  You
could either use the standard web color map:

  Imager->write_multi({ file=>$filename, 
                        type=>'gif',
                        make_colors=>'webmap' },
                      @imgs);

or use a median cut algorithm to built a fairly optimal color map:

  Imager->write_multi({ file=>$filename,
                        type=>'gif',
                        make_colors=>'mediancut' },
                      @imgs);

By default all of the images will use the same global color map, which
will produce a smaller image.  If your images have significant color
differences, you may want to generate a new palette for each image:

  Imager->write_multi({ file=>$filename,
                        type=>'gif',
                        make_colors=>'mediancut',
                        gif_local_map => 1 },
                      @imgs);

which will set the C<gif_local_map> tag in each image to 1.
Alternatively, if you know only some images have different colors, you
can set the tag just for those images:

  $imgs[2]->settag(name=>'gif_local_map', value=>1);
  $imgs[4]->settag(name=>'gif_local_map', value=>1);

and call write_multi() without a C<gif_local_map> parameter, or supply
an arrayref of values for the tag:

  Imager->write_multi({ file=>$filename,
                        type=>'gif',
                        make_colors=>'mediancut',
                        gif_local_map => [ 0, 0, 1, 0, 1 ] },
                      @imgs);

Other useful parameters include C<gif_delay> to control the delay
between frames and C<transp> to control transparency.

=head2 Reading tags after reading an image

This is pretty simple:

  # print the author of a TIFF, if any
  my $img = Imager->new;
  $img->read(file=>$filename, type='tiff') or die $img->errstr;
  my $author = $img->tags(name=>'tiff_author');
  if (defined $author) {
    print "Author: $author\n";
  }

=head1 BUGS

When saving GIF images the program does NOT try to shave off extra
colors if it is possible.  If you specify 128 colors and there are
only 2 colors used - it will have a 128 color table anyway.

=head1 SEE ALSO

Imager(3)

=head1 AUTHOR

Tony Cook <tonyc@cpan.org>, Arnar M. Hrafnkelsson

=cut