File: PNGCodec.java

package info (click to toggle)
java-imaging-utilities 0.14.2%2B3-4
  • links: PTS
  • area: main
  • in suites: jessie, jessie-kfreebsd, wheezy
  • size: 2,304 kB
  • ctags: 3,737
  • sloc: java: 31,190; sh: 238; xml: 30; makefile: 19
file content (2040 lines) | stat: -rw-r--r-- 58,047 bytes parent folder | download | duplicates (2)
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
/*
 * PNGCodec
 * 
 * Copyright (c) 2003, 2004, 2005, 2006 Marco Schmidt.
 * All rights reserved.
 */

package net.sourceforge.jiu.codecs;

import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.DataOutput;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.IOException;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.SimpleTimeZone;
import java.util.zip.CheckedInputStream;
import java.util.zip.Deflater;
import java.util.zip.InflaterInputStream;
import java.util.zip.CRC32;
import net.sourceforge.jiu.data.BilevelImage;
import net.sourceforge.jiu.data.Gray16Image;
import net.sourceforge.jiu.data.Gray8Image;
import net.sourceforge.jiu.data.IntegerImage;
import net.sourceforge.jiu.data.MemoryBilevelImage;
import net.sourceforge.jiu.data.MemoryGray16Image;
import net.sourceforge.jiu.data.MemoryGray8Image;
import net.sourceforge.jiu.data.MemoryPaletted8Image;
import net.sourceforge.jiu.data.MemoryRGB24Image;
import net.sourceforge.jiu.data.MemoryRGB48Image;
import net.sourceforge.jiu.data.Palette;
import net.sourceforge.jiu.data.Paletted8Image;
import net.sourceforge.jiu.data.PixelImage;
import net.sourceforge.jiu.data.RGB24Image;
import net.sourceforge.jiu.data.RGB48Image;
import net.sourceforge.jiu.data.RGBIndex;
import net.sourceforge.jiu.ops.MissingParameterException;
import net.sourceforge.jiu.ops.OperationFailedException;
import net.sourceforge.jiu.util.ArrayConverter;

/**
 * An input stream that reads from an underlying stream of PNG
 * IDAT chunks and skips all header information.
 * PNG uses one or more IDAT chunks to store image data.
 * The resulting stream looks like that:
 * <code>IDAT [chunk size] [compressed data] [checksum] 
 * IDAT [chunk size] [compressed data] [checksum] ...</code>
 * This stream class expects an input stream where the first IDAT chunk name and chunk
 * size have been read already, the stream is thus pointing to the
 * first byte of the first [compressed data] section.
 * The size of that section is given to the constructor.
 * This class then returns calls to read(), counts the bytes it has given 
 * away and, whenever a compressed data section has been consumed, it reads
 * the IDAT chunk and stores its size, using it to determine when the
 * next compressed data section will end.
 * That way, for the caller the stream appears to be one large compressed
 * section.
 * <p>
 * According to the PNG specs the reason for multiple IDAT chunks is as
 * follows:
 * <blockquote>
 * (Multiple IDAT chunks are allowed so that encoders can work in a fixed 
 * amount of memory; typically the chunk size will correspond to the encoder's 
 * buffer size.)
 * </blockquote>
 * <a target="_top" href="http://www.w3.org/TR/PNG#C.IDAT">4.1.3. IDAT Image data</a>
 * <p>
 * If there is a more elegant approach to read multiple IDAT chunks, please
 * let me know.
 * However, reading everything into memory is not an option. 
 * @author Marco Schmidt
 * @since 0.12.0
 */
class PngIdatInputStream extends InputStream
{
	private static final int IDAT = 0x49444154;
	private DataInputStream in;
	private long bytesLeft;

	public PngIdatInputStream(DataInputStream input, long bytes)
	{
		in = input;
		bytesLeft = bytes;
	}

	public int read() throws IOException
	{
		if (bytesLeft == 0)
		{
			skipHeaders();
		}
		bytesLeft--;
		return in.read();
	}

	private void skipHeaders() throws IOException
	{
		do
		{
			//int crc = in.readInt();
			in.readInt(); // skip CRC
			bytesLeft = in.readInt() & 0xffffffffL;
			int type = in.readInt();
			if (IDAT != type)
			{
				throw new IOException("Expected IDAT chunk type, got " + 
					Integer.toHexString(type));
			}
		}
		while (bytesLeft == 0);
	}
}

/**
 * A codec for the Portable Network Graphics (PNG) format.
 * Supports both loading and saving of images.
 * <h3>Usage examples</h3> 
 * <h4>Load an image</h4>
 * The following example code loads an image from a PNG file.
 * Note that you could also use {@link ImageLoader} or {@link net.sourceforge.jiu.gui.awt.ToolkitLoader}
 * which require only a single line of code and can load all formats
 * supported by JIU, including PNG. 
 * <pre>  PNGCodec codec = new PNGCodec();
 *  codec.setFile("image.png", CodecMode.LOAD);
 *  codec.process();
 *  PixelImage image = codec.getImage();</pre>
 * <h4>Save an image</h4>
 * <pre>  PNGCodec codec = new PNGCodec();
 *  codec.setFile("out.png", CodecMode.SAVE);
 *  codec.setImage(image);
 *  codec.setCompressionLevel(Deflater.BEST_COMPRESSION);
 *  codec.appendComment("Copyright (c) 1992 John Doe");
 *  // sets last modification time to current time
 *  codec.setModification(new GregorianCalendar(
 *   new SimpleTimeZone(0, "UTC")));
 *  codec.process();</pre>
 * <h3>Supported storage order types</h3>
 * <h4>Loading</h4>
 * This codec reads both non-interlaced and Adam7 interlaced PNG files.
 * <h4>Saving</h4>
 * This codec only writes non-interlaced PNG files.
 * <h3>Supported color types</h3>
 * <h4>Loading</h4>
 * <ul>
 * <li>Grayscale 1 bit streams are loaded as {@link net.sourceforge.jiu.data.BilevelImage} objects,
 *  2, 4 and 8 bit streams as {@link net.sourceforge.jiu.data.Gray8Image} and 16 bit as
 *  {@link net.sourceforge.jiu.data.Gray16Image} objects.</li>
 * <li>Indexed 1, 2, 4 and 8 bit streams are all loaded as {@link net.sourceforge.jiu.data.Paletted8Image}.</li>
 * <li>RGB truecolor 24 bit streams are loaded as {@link net.sourceforge.jiu.data.RGB24Image},
 *  48 bit streams as {@link net.sourceforge.jiu.data.RGB48Image} objects.</li>
 * </ul> 
 * <h4>Saving</h4>
 * <ul>
 * <li>{@link net.sourceforge.jiu.data.BilevelImage} objects are stored as grayscale 1 bit PNG streams.</li>
 * <li>{@link net.sourceforge.jiu.data.Paletted8Image} objects are stored as indexed 8 bit PNG streams.
 *  Images will always be stored as 8 bit files, even if the palette has only 16, 4 or 2 entries.
 * </li>
 * <li>{@link net.sourceforge.jiu.data.Gray8Image} objects are stored as 8 bit grayscale PNG streams.</li>
 * <li>{@link net.sourceforge.jiu.data.Gray16Image} objects are stored as 16 bit grayscale PNG streams.</li>
 * <li>{@link net.sourceforge.jiu.data.RGB24Image} objects are stored as 24 bit RGB truecolor PNG streams.</li>
 * <li>{@link net.sourceforge.jiu.data.RGB48Image} objects are stored as 48 bit RGB truecolor PNG streams.</li>
 * </ul> 
 * <h3>Transparency information</h3>
 * PNG allows to store different types of transparency information.
 * Full alpha channels, transparent index values, and more.
 * Right now, this JIU codec does not make use of this information and simply
 * skips over it when encountered.
 * <h3>Bounds</h3>
 * This codec regards the bounds concept.
 * If bounds are specified with {@link #setBounds}, the codec will only load or save
 * part of an image.
 * <h3>Metadata</h3>
 * <h4>Loading</h4>
 * <ul>
 * <li>Physical resolution information is loaded from <code>pHYs</code> chunks.
 *  Use {@link #getDpiX} and {@link #getDpiY} to retrieve that information.
 *  after the call to {@link #process}.</li>
 * <li>Textual comments are read from <code>tEXt</code> chunks and can be retrieved
 *  with {@link #getComment} after the call to {@link #process}.</li>
 * </ul>
 * <h4>Saving</h4>
 * <ul>
 *  <li>Physical resolution information (specified with {@link #setDpi})
 *    is stored in a <code>pHYs</code> chunk.</li>
 *  <li>Textual comments (specified with {@link #appendComment}) are stored as <code>tEXt</code> chunks.
 *   The keyword used is <code>Comment</code>.
 *   Each of the {@link #getNumComments} is stored in a chunk of its own.</li>
 *  <li>Time of modification is stored in a <code>tIME</code> chunk.
 *   Use {@link #setModification(Calendar)} to give a point in time to this codec.</li>
 * </ul>
 * <h3>Implementation details</h3>
 * This class relies heavily on the Java runtime library for decompression and 
 * checksum creation.
 * <h3>Background</h3>
 * To learn more about the PNG file format, visit its 
 * <a target="_top" href="http://www.libpng.org/pub/png/">official homepage</a>.
 * There you can find a detailed specification, 
 * test images and existing PNG libraries and PNG-aware applications.
 * The book <em>PNG - The Definitive Guide</em> by Greg Roelofs, published by O'Reilly, 1999,
 * ISBN 1-56592-542-4 is a valuable source of information on PNG.
 * It is out of print, but it can be viewed online and downloaded for offline reading 
 * in its entirety from the site. 
 * @author Marco Schmidt
 * @since 0.12.0
 */
public class PNGCodec extends ImageCodec
{
	private final int CHUNK_CRC32_IEND = 0xae426082;
	private final int CHUNK_SIZE_IHDR = 0x0000000d;
	private final int CHUNK_TYPE_IDAT = 0x49444154;
	private final int CHUNK_TYPE_IEND = 0x49454e44;
	private final int CHUNK_TYPE_IHDR = 0x49484452;
	private final int CHUNK_TYPE_PHYS = 0x70485973;
	private final int CHUNK_TYPE_PLTE = 0x504c5445;
	private final int CHUNK_TYPE_TEXT = 0x74455874;
	private final int CHUNK_TYPE_TIME = 0x74494d45;
	private final int COLOR_TYPE_GRAY = 0;
	private final int COLOR_TYPE_GRAY_ALPHA = 4;
	private final int COLOR_TYPE_INDEXED = 3;
	private final int COLOR_TYPE_RGB = 2;
	private final int COLOR_TYPE_RGB_ALPHA = 6;
	private final int COLOR_TYPE_ALPHA = 4;
	private final int FILTER_TYPE_NONE = 0;
	private final int FILTER_TYPE_SUB = 1;
	private final int FILTER_TYPE_UP = 2;
	private final int FILTER_TYPE_AVERAGE = 3;
	private final int FILTER_TYPE_PAETH = 4;
	private final int COMPRESSION_DEFLATE = 0;
	private final int INTERLACING_NONE = 0;
	private final int INTERLACING_ADAM7 = 1;
	private final int FILTERING_ADAPTIVE = 0;
	private final int MAX_TEXT_SIZE = 512;
	private final int ADAM7_NUM_PASSES = 7;
	private final int DEFAULT_ENCODING_MIN_IDAT_SIZE = 32 * 1024;
	private final int[] ADAM7_COLUMN_INCREMENT = {8, 8, 4, 4, 2, 2, 1};
	private final int[] ADAM7_FIRST_COLUMN = {0, 4, 0, 2, 0, 1, 0};
	private final int[] ADAM7_FIRST_ROW = {0, 0, 4, 0, 2, 0, 1};
	private final int[] ADAM7_ROW_INCREMENT = {8, 8, 8, 4, 4, 2, 2};
	private final byte[] MAGIC_BYTES =
		{(byte)0x89, (byte)0x50, (byte)0x4e, (byte)0x47,
		 (byte)0x0d, (byte)0x0a, (byte)0x1a, (byte)0x0a};

	private boolean alpha;
	private byte[][] buffers;
	private int bpp;
	private CRC32 checksum;
	private CheckedInputStream checkedIn;
	private int chunkCounter;
	private int colorType;
	private int compressionType;
	private int currentBufferIndex;
	private int deflateLevel = Deflater.DEFAULT_COMPRESSION;
	private int deflateStrategy = Deflater.DEFAULT_STRATEGY;
	private int encodingMinIdatSize = DEFAULT_ENCODING_MIN_IDAT_SIZE;
	private int filterType;
	private boolean hasIhdr;
	private int height;
	private IntegerImage image;
	private DataInputStream in;
	private InflaterInputStream infl;
	private int interlaceType;
	private Calendar modification;
	private int numChannels;
	private DataOutput out;
	private Palette palette;
	private int precision;
	private int previousBufferIndex;
	private int width;

	/**
	 * Allocates the right image to private field <code>image</code>,
	 * taking into consideration the fields width, height, precision and colorType.
	 * Assumes that an IHDR chunk has been read and the above mentioned
	 * fields have been initialized and checked for their validity.
	 */ 
	private void allocateImage() throws InvalidFileStructureException, UnsupportedTypeException
	{
		setBoundsIfNecessary(width, height);
		int w = getBoundsWidth();
		int h = getBoundsHeight();
		if (colorType == COLOR_TYPE_GRAY || colorType == COLOR_TYPE_GRAY_ALPHA)
		{
			if (precision == 1)
			{
				image = new MemoryBilevelImage(w, h);
			}
			else
			if (precision <= 8)
			{
				image = new MemoryGray8Image(w, h);
			}
			else
			if (precision == 16)
			{
				image = new MemoryGray16Image(w, h);
			}
		}
		else
		if (colorType == COLOR_TYPE_INDEXED)
		{
			if (palette == null)
			{
				throw new InvalidFileStructureException("No palette found when trying to load indexed image.");
			}
			image = new MemoryPaletted8Image(w, h, palette);
		}
		else
		if (colorType == COLOR_TYPE_RGB || colorType == COLOR_TYPE_RGB_ALPHA)
		{
			if (precision == 8)
			{
				image = new MemoryRGB24Image(w, h);
			}
			else
			{
				image = new MemoryRGB48Image(w, h);
			}
		}
		else
		{
			throw new UnsupportedTypeException("Unsupported image type encountered");
		}
	}

	/**
	 * Checks values {@link #precision} and {@link #colorType}.
	 * A lot of combinations possibly found in an IHDR chunk
	 * are invalid. 
	 * Also initializes {@link #alpha} and {@link #numChannels}.
	 * @throws UnsupportedTypeException if an invalid combination 
	 *  of precision and colorType is found
	 */
	private void checkColorTypeAndPrecision() throws UnsupportedTypeException
	{
		if (colorType != COLOR_TYPE_GRAY &&
		    colorType != COLOR_TYPE_RGB &&
		    colorType != COLOR_TYPE_INDEXED && 
		    colorType != COLOR_TYPE_GRAY_ALPHA && 
		    colorType != COLOR_TYPE_RGB_ALPHA)
		{
			throw new UnsupportedTypeException("Not a valid color type: " + colorType);
		}
		if (precision != 1 && precision != 2 && precision != 4 && precision != 8 && precision != 16)
		{
			throw new UnsupportedTypeException("Invalid precision value: " + precision);
		}
		if (colorType == COLOR_TYPE_INDEXED && precision > 8)
		{
			throw new UnsupportedTypeException("More than eight bits of precision are not allowed for indexed images.");
		}
		if (colorType == COLOR_TYPE_RGB && precision < 8)
		{
			throw new UnsupportedTypeException("Less than eight bits of precision are not allowed for RGB images.");
		}
		alpha = (colorType & COLOR_TYPE_ALPHA) != 0;
		if (colorType == COLOR_TYPE_RGB ||
		    colorType == COLOR_TYPE_RGB_ALPHA)
		{
			numChannels = 3;
		}
		else
		{
			numChannels = 1;
		}
		bpp = computeBytesPerRow(1);
	}

	/**
	 * Computes a number of bytes for a given number of pixels,
	 * regarding precision and availability of an alpha channel.
	 * @param numPixels the number of pixels for which the number
	 *  of bytes necessary to store them is to be computed
	 * @return number of bytes
	 */
	private int computeBytesPerRow(int numPixels)
	{
		if (precision < 8)
		{
			return (numPixels + ((8 / precision) - 1)) / (8 / precision);
		}
		else
		{
			return (numChannels + (alpha ? 1 : 0)) * (precision / 8) * numPixels;
		}
	}

	private int computeColumnsAdam7(int pass)
	{
		switch(pass)
		{
			case(0): return (width + 7) / 8;
			case(1): return (width + 3) / 8;
			case(2): return (width + 3) / 4;
			case(3): return (width + 1) / 4;
			case(4): return (width + 1) / 2;
			case(5): return width / 2;
			case(6): return width;
			default: throw new IllegalArgumentException("Not a valid pass index: " + pass);
		}
	}

	private void fillRowBuffer(int y, byte[] row, int offs)
	{
		PixelImage image = getImage();
		int x1 = getBoundsX1();
		int w = getBoundsWidth();
		if (image instanceof BilevelImage)
		{
			BilevelImage bilevelImage = (BilevelImage)image;
			bilevelImage.getPackedBytes(x1, y, w, row, offs, 0);
		}
		else
		if (image instanceof Gray16Image)
		{
			Gray16Image grayImage = (Gray16Image)image;
			while (w-- > 0)
			{
				short sample = grayImage.getShortSample(x1++, y);
				ArrayConverter.setShortBE(row, offs, sample);
				offs += 2;
			}
		}
		else
		if (image instanceof Gray8Image)
		{
			Gray8Image grayImage = (Gray8Image)image;
			grayImage.getByteSamples(0, getBoundsX1(), y, getBoundsWidth(), 1, row, offs);
		}
		else
		if (image instanceof Paletted8Image)
		{
			Paletted8Image palImage = (Paletted8Image)image;
			palImage.getByteSamples(0, getBoundsX1(), y, getBoundsWidth(), 1, row, offs);
		}
		else
		if (image instanceof RGB24Image)
		{
			RGB24Image rgbImage = (RGB24Image)image;
			while (w-- > 0)
			{
				row[offs++] = rgbImage.getByteSample(RGBIndex.INDEX_RED, x1, y);
				row[offs++] = rgbImage.getByteSample(RGBIndex.INDEX_GREEN, x1, y);
				row[offs++] = rgbImage.getByteSample(RGBIndex.INDEX_BLUE, x1, y);
				x1++;
			}
		}
		else
		if (image instanceof RGB48Image)
		{
			RGB48Image rgbImage = (RGB48Image)image;
			while (w-- > 0)
			{
				short sample = rgbImage.getShortSample(RGBIndex.INDEX_RED, x1, y);
				ArrayConverter.setShortBE(row, offs, sample);
				offs += 2;

				sample = rgbImage.getShortSample(RGBIndex.INDEX_GREEN, x1, y);
				ArrayConverter.setShortBE(row, offs, sample);
				offs += 2;

				sample = rgbImage.getShortSample(RGBIndex.INDEX_BLUE, x1, y);
				ArrayConverter.setShortBE(row, offs, sample);
				offs += 2;

				x1++;
			}
		}
	}

	/**
	  * Creates a four-letter String from the parameter, an <code>int</code>
	  * value, supposed to be storing a chunk name.
	  * @return the chunk name
	  */
	private static String getChunkName(int chunk)
	{
		StringBuffer result = new StringBuffer(4);
		for (int i = 24; i >= 0; i -= 8)
		{
			result.append((char)((chunk >> i) & 0xff));
		}
		return result.toString();
	}

	public String getFormatName()
	{
		return "Portable Network Graphics (PNG)";
	}

	public String[] getMimeTypes()
	{
		return new String[] {"image/png"};
	}

	private static int getPaeth(byte l, byte u, byte nw)
	{
		int a = l & 0xff;
		int b = u & 0xff;
		int c = nw & 0xff;
		int p = a + b - c;
		int pa = p - a;
		if (pa < 0)
		{
			pa = -pa;
		}
		int pb = p - b;
		if (pb < 0)
		{
			pb = -pb;
		} 
		int pc = p - c; 
		if (pc < 0)
		{
			pc = -pc;
		} 
		if (pa <= pb && pa <= pc)
		{
			return a;
		}
		if (pb <= pc)
		{
			return b;
		} 
		return c;
	}

	private void inflateBytes(byte[] buffer, int numBytes) throws InvalidFileStructureException, IOException
	{
		int offset = 0;
		do
		{
			try
			{
				int toRead = numBytes - offset;
				int numRead = infl.read(buffer, offset, toRead);
				if (numRead < 0)
				{
					throw new InvalidFileStructureException("Cannot fill buffer");
				}
				offset += numRead;
			}
			catch (IOException ioe)
			{
				throw new InvalidFileStructureException("Stopped decompressing " + ioe.toString());
			}
		}
		while (offset != numBytes);
	}

	public boolean isLoadingSupported()
	{
		return true;
	}

	public boolean isSavingSupported()
	{
		return true;
	}

	private void load() throws 
		InvalidFileStructureException,
		IOException,
		UnsupportedTypeException,
		WrongFileFormatException
	{
		byte[] magic = new byte[MAGIC_BYTES.length];
		in.readFully(magic);
		for (int i = 0; i < MAGIC_BYTES.length; i++)
		{
			if (magic[i] != MAGIC_BYTES[i])
			{
				throw new WrongFileFormatException("Not a valid PNG input " +
					"stream, wrong magic byte sequence.");
			}
		}
		chunkCounter = 0;
		do
		{
			loadChunk();
			chunkCounter++;
		}
		while (image == null);
		close();
		setImage(image);
	}

	private void loadChunk() throws InvalidFileStructureException, IOException, UnsupportedTypeException
	{
		/*
		 * read chunk size; according to the PNG specs, the size value must not be larger
		 * than 2^31 - 1; to be safe, we treat the value as an unsigned
		 * 32 bit value anyway 
		 */
		long chunkSize = in.readInt() & 0xffffffffL;
		checksum.reset();
		int chunkName = in.readInt();
		// first chunk must be IHDR
		if (chunkCounter == 0 && chunkName != CHUNK_TYPE_IHDR)
		{
			throw new InvalidFileStructureException("First chunk was not IHDR but " + getChunkName(chunkName));
		}
		switch (chunkName)
		{
			// image data chunk
			case(CHUNK_TYPE_IDAT):
			{
				loadImage(chunkSize);
				break;
			}
			// end of image chunk
			case(CHUNK_TYPE_IEND):
			{
				throw new InvalidFileStructureException("Reached IEND chunk but could not load image.");
			}
			case(CHUNK_TYPE_IHDR):
			{
				if (hasIhdr)
				{
					throw new InvalidFileStructureException("More than one IHDR chunk found.");
				}
				if (chunkCounter != 0)
				{
					throw new InvalidFileStructureException("IHDR chunk must be first; found to be chunk #" + (chunkCounter + 1));
				}
				if (chunkSize != CHUNK_SIZE_IHDR)
				{
					throw new InvalidFileStructureException("Expected PNG " +
						"IHDR chunk length to be " + CHUNK_SIZE_IHDR + ", got " +
						chunkSize + ".");
				}
				hasIhdr = true;
				loadImageHeader();
				break;
			}
			case(CHUNK_TYPE_PHYS):
			{
				if (chunkSize == 9)
				{
					byte[] phys = new byte[9];
					in.readFully(phys);
					int x = ArrayConverter.getIntBE(phys, 0);
					int y = ArrayConverter.getIntBE(phys, 4);
					if (phys[8] == 1)
					{
						// unit is meters
						final double INCHES_PER_METER = 100 / 2.54;
						setDpi((int)(x / INCHES_PER_METER), (int)(y / INCHES_PER_METER));
					}
				}
				else
				{
					skip(chunkSize);
				}
				break;
			}
			case(CHUNK_TYPE_PLTE):
			{
				if ((chunkSize % 3) != 0)
				{
					throw new InvalidFileStructureException("Not a valid palette chunk size: " + chunkSize);
				}
				loadPalette(chunkSize / 3);
				break;
			}
			case(CHUNK_TYPE_TEXT):
			{
				if (chunkSize == 0)
				{
				}
				else
				if (chunkSize > MAX_TEXT_SIZE)
				{
					skip(chunkSize);
				}
				else
				{
					StringBuffer text = new StringBuffer((int)chunkSize);
					int i = 0;
					char c;
					do
					{
						c = (char)in.read();
						if (c == 0)
						{
							skip(chunkSize - i - 1);
							break;
						}
						text.append(c);
						i++;
					}
					while (i < chunkSize);
					//System.out.println("text=\"" + text.toString() + "\"");
				}
				break;
			}
			default:
			{
				skip(chunkSize);
			}
		}
		int createdChecksum = (int)checksum.getValue();
		if (image == null)
		{
			// this code doesn't work anymore if we have just read an image
			int chunkChecksum = in.readInt();
			if (createdChecksum != chunkChecksum)
			{
				throw new InvalidFileStructureException("Checksum created on chunk " +
					getChunkName(chunkName) + " " + Integer.toHexString(createdChecksum) +
					" is not equal to checksum read from stream " + 
					Integer.toHexString(chunkChecksum) + 
					"; file is corrupted.");
			}
		}
	}

	/**
	 * Load an image from the current position in the file.
	 * Assumes the last things read from input are an IDAT chunk type and
	 * its size, which is the sole argument of this method.
	 * @param chunkSize size of the IDAT chunk that was just read
	 * @throws InvalidFileStructureException if there are values in the PNG stream that make it invalid
	 * @throws IOException if there were I/O errors when reading
	 * @throws UnsupportedTypeException if something was encountered in the stream that is valid but not supported by this codec
	 */
	private void loadImage(long chunkSize) throws InvalidFileStructureException, IOException, UnsupportedTypeException
	{
		// allocate two byte buffers for current and previous row
		buffers = new byte[2][];
		int numBytes = computeBytesPerRow(width);
		currentBufferIndex = 0;
		previousBufferIndex = 1;
		buffers[currentBufferIndex] = new byte[numBytes];
		buffers[previousBufferIndex] = new byte[numBytes];
		for (int i = 0; i < buffers[previousBufferIndex].length; i++)
		{
			buffers[previousBufferIndex][i] = (byte)0;
		}
		// allocate the correct type of image object for the image type read in the IHDR chunk 
		allocateImage();
		// create a PngIdatInputStream which will skip header information when
		// multiple IDAT chunks are in the input stream
		infl = new InflaterInputStream(new PngIdatInputStream(in, chunkSize));
		switch(interlaceType)
		{
			case(INTERLACING_NONE):
			{
				loadImageNonInterlaced();
				break;
			}
			case(INTERLACING_ADAM7):
			{
				loadImageInterlacedAdam7();
				break;
			}
		}
	}

	/**
	 * Reads data from an IHDR chunk and initializes private fields with it.
	 * Does a lot of checking if read values are valid and supported by this class.
	 * @throws IOException
	 * @throws InvalidFileStructureException
	 * @throws UnsupportedTypeException
	 */
	private void loadImageHeader() throws IOException, InvalidFileStructureException, UnsupportedTypeException
	{
		// WIDTH -- horizontal resolution
		width = in.readInt();
		if (width < 1)
		{
			throw new InvalidFileStructureException("Width must be larger than 0; got " + width);
		}
		// HEIGHT -- vertical resolution
		height = in.readInt();
		if (height < 1)
		{
			throw new InvalidFileStructureException("Height must be larger than 0; got " + height);
		}
		// PRECISION -- bits per sample
		precision = in.read();
		// COLOR TYPE -- indexed, paletted, grayscale, optionally alpha
		colorType = in.read();
		// check for invalid combinations of color type and precision
		// and initialize alpha and numChannels
		checkColorTypeAndPrecision();
		// COMPRESSION TYPE -- only Deflate is defined
		compressionType = in.read();
		if (compressionType != COMPRESSION_DEFLATE)
		{
			throw new UnsupportedTypeException("Unsupported compression type: " +
				compressionType + ".");
		}
		// FILTER TYPE -- only Adaptive is defined
		filterType = in.read();
		if (filterType != FILTERING_ADAPTIVE)
		{
			throw new UnsupportedTypeException("Only 'adaptive filtering' is supported right now; got " + filterType);
		}
		// INTERLACE TYPE -- order of storage of image data
		interlaceType = in.read();
		if (interlaceType != INTERLACING_NONE &&
		    interlaceType != INTERLACING_ADAM7)
		{
			throw new UnsupportedTypeException("Only 'no interlacing' and 'Adam7 interlacing' are supported; got " + interlaceType);
		}
	}

	private void loadImageInterlacedAdam7() throws InvalidFileStructureException, IOException, UnsupportedTypeException
	{
		final int TOTAL_LINES = ADAM7_NUM_PASSES * height;
		for (int pass = 0; pass < ADAM7_NUM_PASSES; pass++)
		{
			currentBufferIndex = 0;
			previousBufferIndex = 1;
			byte[] previousBuffer = buffers[previousBufferIndex];
			for (int x = 0; x < previousBuffer.length; x++)
			{
				previousBuffer[x] = 0;
			}
			int y = ADAM7_FIRST_ROW[pass];
			int destY = y - getBoundsY1();
			int numColumns = computeColumnsAdam7(pass);
			if (numColumns == 0)
			{
				// this pass contains no data; skip to next pass
				setProgress((pass + 1) * height, TOTAL_LINES);
				continue;
			}
			int numBytes = computeBytesPerRow(numColumns);
			while (y < height)
			{
				previousBuffer = buffers[previousBufferIndex];
				byte[] currentBuffer = buffers[currentBufferIndex];
				int rowFilterType = readFilterType();
				inflateBytes(currentBuffer, numBytes);
				reverseFilter(rowFilterType, currentBuffer, previousBuffer, numBytes);
				if (isRowRequired(y))
				{
					storeInterlacedAdam7(pass, destY, currentBuffer);
				}
				int progressY = y;
				if (pass > 0)
				{
					progressY += pass * height;
				}
				setProgress(progressY, TOTAL_LINES);
				y += ADAM7_ROW_INCREMENT[pass];
				destY += ADAM7_ROW_INCREMENT[pass];
				currentBufferIndex = 1 - currentBufferIndex;
				previousBufferIndex = 1 - previousBufferIndex;
			}
		}
	}

	private void loadImageNonInterlaced() throws InvalidFileStructureException, IOException, UnsupportedTypeException
	{
		int linesToRead = getBoundsY2() + 1;
		int rowLength = computeBytesPerRow(width);
		for (int y = 0, destY = - getBoundsY1(); y <= getBoundsY2(); y++, destY++)
		{
			byte[] currentBuffer = buffers[currentBufferIndex];
			byte[] previousBuffer = buffers[previousBufferIndex];
			int rowFilterType = readFilterType();
			inflateBytes(currentBuffer, rowLength);
			reverseFilter(rowFilterType, currentBuffer, previousBuffer, rowLength);
			if (isRowRequired(y))
			{
				storeNonInterlaced(destY, currentBuffer);
			}
			setProgress(y, linesToRead);
			previousBufferIndex = 1 - previousBufferIndex;
			currentBufferIndex = 1 - currentBufferIndex;
		}
	}

	private void loadPalette(long numEntries) throws InvalidFileStructureException, IOException
	{
		if (palette != null)
		{
			throw new InvalidFileStructureException("More than one palette in input stream.");
		}
		if (numEntries < 1)
		{
			throw new InvalidFileStructureException("Number of palette entries must be at least 1.");
		}
		if (numEntries > 256)
		{
			throw new InvalidFileStructureException("Number of palette entries larger than 256: " + numEntries);
		}
		palette = new Palette((int)numEntries);
		int index = 0;
		do
		{
			palette.putSample(Palette.INDEX_RED, index, in.read() & 0xff);
			palette.putSample(Palette.INDEX_GREEN, index, in.read() & 0xff);
			palette.putSample(Palette.INDEX_BLUE, index, in.read() & 0xff);
			index++;
		}
		while (index != numEntries);
	}

	public static void main(String[] args) throws Exception
	{
		PNGCodec codec = new PNGCodec();
		codec.setFile(args[0], CodecMode.LOAD);
		codec.process();
		codec.close();
		PixelImage image = codec.getImage();
		codec = new PNGCodec();
		codec.setFile(args[1], CodecMode.SAVE);
		codec.setImage(image);
		codec.setDpi(300, 300);
		codec.appendComment("Test comment #1.");
		codec.appendComment("And test comment #2.");
		codec.setModification(new GregorianCalendar(new SimpleTimeZone(0, "UTC")));
		codec.process();
		codec.close();
	}

	public void process() throws
		InvalidFileStructureException,
		MissingParameterException,
		OperationFailedException,
		UnsupportedTypeException,
		WrongFileFormatException
	{
		initModeFromIOObjects();
		if (getMode() == CodecMode.LOAD)
		{
			try
			{
				if (getImageIndex() != 0)
				{
					throw new InvalidImageIndexException("PNG streams can only store one image; " + 
						"index " + getImageIndex() + " is thus not valid.");
				}
				InputStream input = getInputStream();
				if (input == null)
				{
					throw new MissingParameterException("InputStream object missing.");
				}
				checksum = new CRC32();
				checkedIn = new CheckedInputStream(input, checksum);
				in = new DataInputStream(checkedIn);
				load();
			}
			catch (IOException ioe)
			{
				throw new OperationFailedException("I/O failure: " + ioe.toString());
			}
		}
		else
		if (getMode() == CodecMode.SAVE)
		{
			try
			{
				PixelImage image = getImage(); 
				if (image == null)
				{
					throw new MissingParameterException("Need image for saving.");
				}
				out = getOutputAsDataOutput();
				if (out == null)
				{
					throw new MissingParameterException("Could not retrieve non-null DataOutput object for saving.");
				}
				setBoundsIfNecessary(image.getWidth(), image.getHeight());
				save();
			}
			catch (IOException ioe)
			{
				throw new OperationFailedException("I/O failure: " + ioe.toString());
			}
		}
		else
		{
			throw new OperationFailedException("Unknown codec mode: " + getMode());
		}
	}

	private int readFilterType() throws InvalidFileStructureException, IOException
	{
		int filterType = infl.read();
		if (filterType >= 0 && filterType <= 4)
		{
			return filterType;
		}
		else
		{
			throw new InvalidFileStructureException("Valid filter types are from 0 to 4; got " + filterType);
		}
	}

	private void reverseFilter(int rowFilterType, byte[] buffer, byte[] prev, int numBytes) throws UnsupportedTypeException
	{
		switch(rowFilterType)
		{
			case(FILTER_TYPE_NONE):
			{
				break;
			}
			case(FILTER_TYPE_SUB):
			{
				for (int x = 0, px = -bpp; x < numBytes; x++, px++)
				{
					byte currXMinusBpp;
					if (px < 0)
					{
						currXMinusBpp = 0;
					}
					else
					{
						currXMinusBpp = buffer[px];
					}
					buffer[x] = (byte)(buffer[x] + currXMinusBpp);
				}
				break;
			}
			case(FILTER_TYPE_UP):
			{
				for (int x = 0; x < numBytes; x++)
				{
					buffer[x] = (byte)(buffer[x] + prev[x]);
				}
				break;
			}
			case(FILTER_TYPE_AVERAGE):
			{
				for (int x = 0, px = -bpp; x < numBytes; x++, px++)
				{
					int currX = buffer[x] & 0xff;
					int currXMinus1;
					if (px < 0)
					{
						currXMinus1 = 0;
					}
					else
					{
						currXMinus1 = buffer[px] & 0xff;
					}
					int prevX = prev[x] & 0xff;
					int result = currX + ((currXMinus1 + prevX) / 2);
					byte byteResult = (byte)result;
					buffer[x] = byteResult;
				}
				break;
			}
			case(FILTER_TYPE_PAETH):
			{
				for (int x = 0, px = -bpp; x < numBytes; x++, px++)
				{
					byte currXMinusBpp; 
					byte prevXMinusBpp;
					if (px < 0)
					{
						currXMinusBpp = 0;
						prevXMinusBpp = 0;
					}
					else
					{
						currXMinusBpp = buffer[px];
						prevXMinusBpp = prev[px];
					}
					buffer[x] = (byte)(buffer[x] + getPaeth(currXMinusBpp, prev[x], prevXMinusBpp));
				}
				break;
			}
			default:
			{
				throw new UnsupportedTypeException("Unknown filter type: " + rowFilterType);
			}
		}
	}

	private void save() throws IOException
	{
		// write 8 byte PNG signature
		out.write(MAGIC_BYTES);
		// write IHDR (image header) chunk
		saveIhdrChunk();
		// write pHYs chunk (physical resolution) if data is available
		savePhysChunk();
		// write tEXt chunks if comments are available
		saveTextChunks();
		// write tIME chunk if modification time was set
		saveTimeChunk();
		// write PLTE chunk if necessary
		savePlteChunk();
		// write IDAT chunk
		saveImage();
		// write IEND chunk
		saveIendChunk();
		close();		
	}

	private void saveChunk(int chunkType, int chunkSize, byte[] data) throws IOException
	{
		// set up array with chunk size and type
		byte[] intArray = new byte[8];
		ArrayConverter.setIntBE(intArray, 0, chunkSize);
		ArrayConverter.setIntBE(intArray, 4, chunkType);
		// write chunk size, type and data
		out.write(intArray, 0, 8);
		out.write(data, 0, chunkSize);
		// create checksum on type and data
		CRC32 checksum = new CRC32();
		checksum.reset();
		checksum.update(intArray, 4, 4);
		checksum.update(data, 0, chunkSize);
		// put checksum into byte array
		ArrayConverter.setIntBE(intArray, 0, (int)checksum.getValue());
		// and write it to output
		out.write(intArray, 0, 4);
	}

	private void saveIendChunk() throws IOException
	{
		out.writeInt(0);
		out.writeInt(CHUNK_TYPE_IEND);
		out.writeInt(CHUNK_CRC32_IEND);
	}

	private void saveIhdrChunk() throws IOException
	{
		byte[] buffer = new byte[CHUNK_SIZE_IHDR];
		width = getBoundsWidth();
		ArrayConverter.setIntBE(buffer, 0, width);
		height = getBoundsHeight();
		ArrayConverter.setIntBE(buffer, 4, height);
		PixelImage image = getImage();
		alpha = false;
		numChannels = 1;
		if (image instanceof BilevelImage)
		{
			precision = 1;
			colorType = COLOR_TYPE_GRAY;
		}
		else
		if (image instanceof Gray16Image)
		{
			precision = 16;
			colorType = COLOR_TYPE_GRAY;
		}
		else
		if (image instanceof Gray8Image)
		{
			precision = 8;
			colorType = COLOR_TYPE_GRAY;
		}
		else
		if (image instanceof Paletted8Image)
		{
			precision = 8;
			colorType = COLOR_TYPE_INDEXED;
		}
		else
		if (image instanceof RGB24Image)
		{
			numChannels = 3;
			precision = 8;
			colorType = COLOR_TYPE_RGB;
		}
		else
		if (image instanceof RGB48Image)
		{
			numChannels = 3;
			precision = 16;
			colorType = COLOR_TYPE_RGB;
		}
		buffer[8] = (byte)precision;
		buffer[9] = (byte)colorType;
		compressionType = COMPRESSION_DEFLATE;
		buffer[10] = (byte)compressionType;
		filterType = FILTERING_ADAPTIVE;
		buffer[11] = (byte)filterType;
		interlaceType = INTERLACING_NONE;
		buffer[12] = (byte)interlaceType;
		saveChunk(CHUNK_TYPE_IHDR, CHUNK_SIZE_IHDR, buffer);
	}

	private void saveImage() throws IOException
	{
		switch(interlaceType)
		{
			case(INTERLACING_NONE):
			{
				saveImageNonInterlaced();
				break;
			}
		}
	}

	private void saveImageNonInterlaced() throws IOException
	{
		int bytesPerRow = computeBytesPerRow(getBoundsWidth());
		byte[] rowBuffer = new byte[bytesPerRow + 1];
		byte[] outBuffer = new byte[Math.max(encodingMinIdatSize, bytesPerRow + 1)];
		int outOffset = 0;
		int numDeflated;
		Deflater defl = new Deflater(deflateLevel);
		defl.setStrategy(deflateStrategy);
		for (int y = getBoundsY1(); y <= getBoundsY2(); y++)
		{
			// fill row buffer
			rowBuffer[0] = (byte)FILTER_TYPE_NONE;
			fillRowBuffer(y, rowBuffer, 1);
			// give it to compressor 
			defl.setInput(rowBuffer);
			// store compressed data in outBuffer 
			do
			{
				numDeflated = defl.deflate(outBuffer, outOffset, outBuffer.length - outOffset);
				outOffset += numDeflated;
				if (outOffset == outBuffer.length)
				{
					saveChunk(CHUNK_TYPE_IDAT,  outOffset, outBuffer);
					outOffset = 0;
				}
			}
			while (numDeflated > 0);
			setProgress(y - getBoundsY1(), getBoundsHeight());
		}
		// tell Deflater that it got all the input
		defl.finish();
		// retrieve remaining compressed data from defl to outBuffer  
		do
		{
			numDeflated = defl.deflate(outBuffer, outOffset, outBuffer.length - outOffset);
			outOffset += numDeflated;
			if (outOffset == outBuffer.length)
			{
				saveChunk(CHUNK_TYPE_IDAT,  outOffset, outBuffer);
				outOffset = 0;
			}
		}
		while (numDeflated > 0);
		// write final IDAT chunk if necessary
		if (outOffset > 0)
		{
			saveChunk(CHUNK_TYPE_IDAT,  outOffset, outBuffer);
		}
	}

	private void savePhysChunk() throws IOException
	{
		int dpiX = getDpiX();
		int dpiY = getDpiY();
		if (dpiX < 1 || dpiY < 1)
		{
			return;
		}
		byte[] data = new byte[9];
		int ppuX = (int)(dpiX * (100 / 2.54));
		int ppuY = (int)(dpiY * (100 / 2.54));
		ArrayConverter.setIntBE(data, 0, ppuX);
		ArrayConverter.setIntBE(data, 4, ppuY);
		data[8] = 1; // unit is the meter
		saveChunk(CHUNK_TYPE_PHYS, data.length, data);
	}

	private void savePlteChunk() throws IOException
	{
		if (colorType != COLOR_TYPE_INDEXED)
		{
			return;
		}
		Paletted8Image image = (Paletted8Image)getImage();
		Palette pal = image.getPalette();
		int numEntries = pal.getNumEntries();
		byte[] data = new byte[numEntries * 3];
		for (int i = 0, j = 0; i < numEntries; i++, j += 3)
		{
			data[j] = (byte)pal.getSample(RGBIndex.INDEX_RED, i);
			data[j + 1] = (byte)pal.getSample(RGBIndex.INDEX_GREEN, i);
			data[j + 2] = (byte)pal.getSample(RGBIndex.INDEX_BLUE, i);
		}
		saveChunk(CHUNK_TYPE_PLTE, data.length, data);
	}

	private void saveTextChunks() throws IOException
	{
		int index = 0;
		while (index < getNumComments())
		{
			String comment = getComment(index++);
			comment = "Comment\000" + comment;
			byte[] data = comment.getBytes("ISO-8859-1");
			saveChunk(CHUNK_TYPE_TEXT, data.length, data);
		}
	}

	private void saveTimeChunk() throws IOException
	{
		if (modification == null)
		{
			return;
		}
		byte[] data = new byte[7];
		ArrayConverter.setShortBE(data, 0, (short)modification.get(Calendar.YEAR));
		data[2] = (byte)(modification.get(Calendar.MONTH) + 1);
		data[3] = (byte)modification.get(Calendar.DAY_OF_MONTH);
		data[4] = (byte)modification.get(Calendar.HOUR_OF_DAY);
		data[5] = (byte)modification.get(Calendar.MINUTE);
		data[6] = (byte)modification.get(Calendar.SECOND);
		saveChunk(CHUNK_TYPE_TIME, data.length, data);
	}

	/**
	 * Sets the compression level to be used with the underlying
	 * {@link java.util.zip.Deflater} object which does the compression.
	 * If no value is specified, {@link java.util.zip.Deflater#DEFAULT_COMPRESSION}
	 * is used.  
	 * @param newLevel compression level, from 0 to 9, 0 being fastest 
	 *  and compressing worst and 9 offering highest compression and taking
	 *  the most time 
	 */
	public void setCompressionLevel(int newLevel)
	{
		if (newLevel >= 0 && newLevel <= 9)
		{
			deflateLevel = newLevel;
		}
		else
		{
			throw new IllegalArgumentException("Compression level must be from 0..9; got " + newLevel);
		}
	}

	/**
	 * Sets the compression strategy to be used with the underlying
	 * {@link java.util.zip.Deflater} object which does the compression.
	 * If no value is specified, {@link java.util.zip.Deflater#DEFAULT_STRATEGY}
	 * is used.  
	 * @param newStrategy one of Deflater's strategy values: 
	 *  {@link java.util.zip.Deflater#DEFAULT_STRATEGY},
	 *  {@link java.util.zip.Deflater#FILTERED},
	 *  {@link java.util.zip.Deflater#HUFFMAN_ONLY}
	 */
	public void setCompressionStrategy(int newStrategy)
	{
		if (newStrategy == Deflater.FILTERED ||
		    newStrategy == Deflater.DEFAULT_STRATEGY ||
		    newStrategy == Deflater.HUFFMAN_ONLY)
		{
			deflateStrategy = newStrategy;
		}
		else
		{
			throw new IllegalArgumentException("Unknown compression strategy: " + newStrategy);
		}
	}

	/**
	 * Sets the size of IDAT chunks generated when encoding.
	 * If this method is never called, a default value of 32768 bytes (32 KB) is used.
	 * Note that a byte array of the size of the value you specify here is allocated,
	 * so make sure that you keep the value small enough to stay within a
	 * system's memory.
	 * <p>
	 * Compressed image data is spread over several IDAT chunks by this codec.
	 * The length of the compressed data of a complete image is known only after the complete image 
	 * has been encoded.
	 * With PNG, that length value has to be stored before the compressed data as a chunk size value.
	 * This codec is supposed to work with {@link java.io.OutputStream} objects,
	 * so seeking back to adjust the chunk size value of an IDAT chunk is not
	 * possible.
	 * That's why all data of a chunk is compressed into a memory buffer.
	 * Whenever the buffer gets full, it is written to output as an IDAT chunk.
	 * <p>
	 * Note that the last IDAT chunk may be smaller than the size defined here.
	 * @param newSize size of encoding compressed data buffer
	 */
	public void setEncodingIdatSize(int newSize)
	{
		if (newSize < 1)
		{
			throw new IllegalArgumentException("Minimum IDAT chunk size must be 1 or larger.");
		}
		encodingMinIdatSize = newSize;
	}

	public void setFile(String fileName, CodecMode codecMode) throws IOException, UnsupportedCodecModeException
	{
		if (codecMode == CodecMode.LOAD)
		{
			setInputStream(new BufferedInputStream(new FileInputStream(fileName)));
		}
		else
		{
			super.setFile(fileName, codecMode);
		}
	}

	/**
	 * Sets date and time of last modification of the image to be stored in a PNG stream
	 * when saving.
	 * Make sure the argument object has UTC as time zone
	 * (<a target="_top" href="http://www.w3.org/TR/PNG#C.tIME">as
	 * demanded by the PNG specs)</a>.
	 * If you want the current time and date, use 
	 * <code>new GregorianCalendar(new SimpleTimeZone(0, "UTC"))</code>
	 * as parameter for this method.
	 * @param time time of last modification of the image
	 */
	public void setModification(Calendar time)
	{
		modification = time;
	}

	/**
	 * Skips a number of bytes in the input stream.
	 * @param num number of bytes to be skipped
	 * @throws IOException if there were I/O errors
	 */
	private void skip(long num) throws IOException
	{
		while (num > 0)
		{
			long numSkipped = in.skip(num);
			if (numSkipped > 0)
			{
				num -= numSkipped;
			}
		}
	}

	private void storeInterlacedAdam7(int pass, int y, byte[] buffer)
	{
		switch(colorType)
		{
			case(COLOR_TYPE_GRAY):
			{
				storeInterlacedAdam7Gray(pass, y, buffer);
				break;
			}
			case(COLOR_TYPE_RGB):
			{
				storeInterlacedAdam7Rgb(pass, y, buffer);
				break;
			}
			case(COLOR_TYPE_RGB_ALPHA):
			{
				storeInterlacedAdam7RgbAlpha(pass, y, buffer);
				break;
			}
			case(COLOR_TYPE_GRAY_ALPHA):
			{
				storeInterlacedAdam7GrayAlpha(pass, y, buffer);
				break;
			}
			case(COLOR_TYPE_INDEXED):
			{
				storeInterlacedAdam7Indexed(pass, y, buffer);
				break;
			}
		}
	}

	private void storeInterlacedAdam7Gray(int pass, int y, byte[] buffer)
	{
		int x = ADAM7_FIRST_COLUMN[pass];
		final int incr = ADAM7_COLUMN_INCREMENT[pass];
		final int x1 = getBoundsX1();
		final int x2 = getBoundsX2();
		int offset = 0;
		int numColumns = computeColumnsAdam7(pass);
		int numPackedBytes = computeBytesPerRow(numColumns);
		byte[] dest = new byte[numColumns + 7];
		switch(precision)
		{
			case(1):
			{
				BilevelImage bilevelImage = (BilevelImage)image;
				ArrayConverter.decodePacked1Bit(buffer, 0, dest, 0, numPackedBytes);
				while (x <= x2)
				{
					if (x >= x1)
					{
						if (dest[offset] == 0)
						{
							bilevelImage.putBlack(x - x1, y);
						}
						else
						{
							bilevelImage.putWhite(x - x1, y);
						}
					}
					x += incr;
					offset++;
				}
				break;
			}
			case(2):
			{
				Gray8Image grayImage = (Gray8Image)image;
				ArrayConverter.convertPacked2BitIntensityTo8Bit(buffer, 0, dest, 0, numPackedBytes);
				while (x <= x2)
				{
					if (x >= x1)
					{
						grayImage.putByteSample(x - x1, y, dest[offset]);
					}
					x += incr;
					offset++;
				}
				break;
			}
			case(4):
			{
				Gray8Image grayImage = (Gray8Image)image;
				ArrayConverter.convertPacked4BitIntensityTo8Bit(buffer, 0, dest, 0, numPackedBytes);
				while (x <= x2)
				{
					if (x >= x1)
					{
						grayImage.putByteSample(x - x1, y, dest[offset]);
					}
					x += incr;
					offset++;
				}
				break;
			}
			case(8):
			{
				Gray8Image grayImage = (Gray8Image)image;
				while (x <= x2)
				{
					if (x >= x1)
					{
						grayImage.putSample(x - x1, y, buffer[offset]);
					}
					x += incr;
					offset++;
				}
				break;
			}
			case(16):
			{
				Gray16Image grayImage = (Gray16Image)image;
				while (x <= x2)
				{
					if (x >= x1)
					{
						int sample = (buffer[offset] & 0xff) << 8;
						sample |= (buffer[offset + 1] & 0xff);
						grayImage.putSample(x, y, sample);
					}
					x += incr;
					offset += 2;
				}
				break;
			}
		}
	}

	private void storeInterlacedAdam7GrayAlpha(int pass, int y, byte[] buffer)
	{
		int x = ADAM7_FIRST_COLUMN[pass];
		final int incr = ADAM7_COLUMN_INCREMENT[pass];
		final int x1 = getBoundsX1();
		final int x2 = getBoundsX2();
		int offset = 0;
		switch(precision)
		{
			case(8):
			{
				Gray8Image grayImage = (Gray8Image)image;
				while (x <= x2)
				{
					if (x >= x1)
					{
						grayImage.putSample(x - x1, y, buffer[offset]);
						// alpha
					}
					x += incr;
					offset += 2;
				}
				break;
			}
			case(16):
			{
				Gray16Image grayImage = (Gray16Image)image;
				while (x <= x2)
				{
					if (x >= x1)
					{
						int sample = (buffer[offset] & 0xff) << 8;
						sample |= (buffer[offset + 1] & 0xff);
						grayImage.putSample(x, y, sample);
						// store alpha
					}
					x += incr;
					offset += 4;
				}
				break;
			}
		}
	}

	private void storeInterlacedAdam7Indexed(int pass, int y, byte[] buffer)
	{
		Paletted8Image palImage = (Paletted8Image)image;
		int x = ADAM7_FIRST_COLUMN[pass];
		final int incr = ADAM7_COLUMN_INCREMENT[pass];
		final int x1 = getBoundsX1();
		final int x2 = getBoundsX2();
		int offset = 0;
		int numColumns = computeColumnsAdam7(pass);
		int numPackedBytes = computeBytesPerRow(numColumns);
		byte[] dest = new byte[numColumns + 7];
		switch(precision)
		{
			case(1):
			{
				ArrayConverter.decodePacked1Bit(buffer, 0, dest, 0, numPackedBytes);
				while (x <= x2)
				{
					if (x >= x1)
					{
						palImage.putByteSample(x - x1, y, dest[offset]);
					}
					x += incr;
					offset++;
				}
				break;
			}
			case(2):
			{
				ArrayConverter.decodePacked2Bit(buffer, 0, dest, 0, numPackedBytes);
				while (x <= x2)
				{
					if (x >= x1)
					{
						palImage.putByteSample(x - x1, y, dest[offset]);
					}
					x += incr;
					offset++;
				}
				break;
			}
			case(4):
			{
				ArrayConverter.decodePacked4Bit(buffer, 0, dest, 0, numPackedBytes);
				while (x <= x2)
				{
					if (x >= x1)
					{
						palImage.putByteSample(x - x1, y, dest[offset]);
					}
					x += incr;
					offset++;
				}
				break;
			}
			case(8):
			{
				while (x <= x2)
				{
					if (x >= x1)
					{
						palImage.putSample(x - x1, y, buffer[offset]);
					}
					x += incr;
					offset++;
				}
				break;
			}
		}
	}

	private void storeInterlacedAdam7Rgb(int pass, int y, byte[] buffer)
	{
		int x = ADAM7_FIRST_COLUMN[pass];
		final int x1 = getBoundsX1();
		final int x2 = getBoundsX2();
		final int incr = ADAM7_COLUMN_INCREMENT[pass];
		int offset = 0;
		if (precision == 8)
		{
			RGB24Image rgbImage = (RGB24Image)image;
			while (x <= x2)
			{
				if (x >= x1)
				{
					rgbImage.putSample(RGB24Image.INDEX_RED, x, y, buffer[offset]);
					rgbImage.putSample(RGB24Image.INDEX_GREEN, x, y, buffer[offset + 1]);
					rgbImage.putSample(RGB24Image.INDEX_BLUE, x, y, buffer[offset + 2]);
				}
				x += incr;
				offset += 3;
			}
		}
		else
		if (precision == 16)
		{
			RGB48Image rgbImage = (RGB48Image)image;
			while (x <= x2)
			{
				if (x >= x1)
				{
					int red = (buffer[offset] & 0xff) << 8;
					red |= buffer[offset + 1] & 0xff;
					rgbImage.putSample(RGB24Image.INDEX_RED, x, y, red);
	
					int green = (buffer[offset + 2] & 0xff) << 8;
					green |= buffer[offset + 3] & 0xff;
					rgbImage.putSample(RGB24Image.INDEX_GREEN, x, y, green);
		
					int blue = (buffer[offset + 4] & 0xff) << 8;
					blue |= buffer[offset + 5] & 0xff;
					rgbImage.putSample(RGB24Image.INDEX_BLUE, x, y, blue);
				}
				x += incr;
				offset += 6;
			}
		}
	}

	private void storeInterlacedAdam7RgbAlpha(int pass, int y, byte[] buffer)
	{
		int x = ADAM7_FIRST_COLUMN[pass];
		final int x1 = getBoundsX1();
		final int x2 = getBoundsX2();
		final int incr = ADAM7_COLUMN_INCREMENT[pass];
		int offset = 0;
		if (precision == 8)
		{
			RGB24Image rgbImage = (RGB24Image)image;
			while (x <= x2)
			{
				if (x >= x1)
				{
					rgbImage.putSample(RGB24Image.INDEX_RED, x, y, buffer[offset]);
					rgbImage.putSample(RGB24Image.INDEX_GREEN, x, y, buffer[offset + 1]);
					rgbImage.putSample(RGB24Image.INDEX_BLUE, x, y, buffer[offset + 2]);
					// store alpha
				}
				x += incr;
				offset += 4;
			}
		}
		else
		if (precision == 16)
		{
			RGB48Image rgbImage = (RGB48Image)image;
			while (x <= x2)
			{
				if (x >= x1)
				{
					int red = (buffer[offset] & 0xff) << 8;
					red |= buffer[offset + 1] & 0xff;
					rgbImage.putSample(RGB24Image.INDEX_RED, x, y, red);
	
					int green = (buffer[offset + 2] & 0xff) << 8;
					green |= buffer[offset + 3] & 0xff;
					rgbImage.putSample(RGB24Image.INDEX_GREEN, x, y, green);
		
					int blue = (buffer[offset + 4] & 0xff) << 8;
					blue |= buffer[offset + 5] & 0xff;
					rgbImage.putSample(RGB24Image.INDEX_BLUE, x, y, blue);
					
					// store alpha
				}
				x += incr;
				offset += 8;
			}
		}
	}


	private void storeNonInterlaced(int y, byte[] buffer)
	{
		switch(colorType)
		{
			case(COLOR_TYPE_GRAY):
			{
				storeNonInterlacedGray(y, buffer);
				break;
			}
			case(COLOR_TYPE_GRAY_ALPHA):
			{
				storeNonInterlacedGrayAlpha(y, buffer);
				break;
			}
			case(COLOR_TYPE_INDEXED):
			{
				storeNonInterlacedIndexed(y, buffer);
				break;
			}
			case(COLOR_TYPE_RGB):
			{
				storeNonInterlacedRgb(y, buffer);
				break;
			}
			case(COLOR_TYPE_RGB_ALPHA):
			{
				storeNonInterlacedRgbAlpha(y, buffer);
				break;
			}
		}
	}

	private void storeNonInterlacedGray(int y, byte[] buffer)
	{
		switch(precision)
		{
			case(1):
			{
				BilevelImage bilevelImage = (BilevelImage)image;
				int x1 = getBoundsX1();
				bilevelImage.putPackedBytes(0, y, getBoundsWidth(), buffer, x1 / 8, x1 % 8);
				break;
			}
			case(2):
			{
				Gray8Image grayImage = (Gray8Image)image;
				byte[] dest = new byte[width + 3];
				ArrayConverter.convertPacked2BitIntensityTo8Bit(buffer, 0, dest, 0, buffer.length);
				grayImage.putByteSamples(0, 0, y, getBoundsWidth(), 1, dest, getBoundsX1());
				break;
			}
			case(4):
			{
				Gray8Image grayImage = (Gray8Image)image;
				byte[] dest = new byte[width + 1];
				ArrayConverter.convertPacked4BitIntensityTo8Bit(buffer, 0, dest, 0, buffer.length);
				grayImage.putByteSamples(0, 0, y, getBoundsWidth(), 1, dest, getBoundsX1());
				break;
			}
			case(8):
			{
				Gray8Image grayImage = (Gray8Image)image;
				int offset = getBoundsX1();
				int x = 0;
				int k = getBoundsWidth();
				while (k > 0)
				{
					grayImage.putSample(0, x++, y, buffer[offset++]);
					k--;
				}
				break;
			}
			case(16):
			{
				Gray16Image grayImage = (Gray16Image)image;
				int offset = getBoundsX1();
				int x = 0;
				int k = getBoundsWidth();
				while (k > 0)
				{
					int sample = (buffer[offset++] & 0xff) << 8;
					sample |= (buffer[offset++] & 0xff);
					grayImage.putSample(x++, y, sample);
					k--;
				}
				break;
			}
		}
	}

	private void storeNonInterlacedGrayAlpha(int y, byte[] buffer)
	{
		switch(precision)
		{
			case(8):
			{
				Gray8Image grayImage = (Gray8Image)image;
				int offset = getBoundsX1();
				int x = 0;
				int k = getBoundsWidth();
				while (k > 0)
				{
					grayImage.putSample(0, x++, y, buffer[offset++]);
					offset++; // skip alpha; should be stored in a TransparencyInformation object
					k--;
				}
				break;
			}
			case(16):
			{
				Gray16Image grayImage = (Gray16Image)image;
				int offset = getBoundsX1();
				int x = 0;
				int k = getBoundsWidth();
				while (k > 0)
				{
					int sample = (buffer[offset++] & 0xff) << 8;
					sample |= (buffer[offset++] & 0xff);
					grayImage.putSample(x++, y, sample);
					offset += 2; // skip alpha;  TODO: store in TransparencyInformation object
					k--;
				}
				break;
			}
		}
	}

	private void storeNonInterlacedIndexed(int y, byte[] buffer)
	{
		Paletted8Image palImage = (Paletted8Image)image;
		switch(precision)
		{
			case(1):
			{
				byte[] dest = new byte[width + 7];
				ArrayConverter.decodePacked1Bit(buffer, 0, dest, 0, buffer.length);
				palImage.putByteSamples(0, 0, y, getBoundsWidth(), 1, dest, getBoundsX1());
				break;
			}
			case(2):
			{
				byte[] dest = new byte[width + 3];
				ArrayConverter.decodePacked2Bit(buffer, 0, dest, 0, buffer.length);
				palImage.putByteSamples(0, 0, y, getBoundsWidth(), 1, dest, getBoundsX1());
				break;
			}
			case(4):
			{
				byte[] dest = new byte[width + 1];
				ArrayConverter.decodePacked4Bit(buffer, 0, dest, 0, buffer.length);
				palImage.putByteSamples(0, 0, y, getBoundsWidth(), 1, dest, getBoundsX1());
				break;
			}
			case(8):
			{
				int offset = getBoundsX1();
				int x = 0;
				int k = getBoundsWidth();
				while (k > 0)
				{
					palImage.putSample(0, x++, y, buffer[offset++]);
					k--;
				}
				break;
			}
		}
	}

	private void storeNonInterlacedRgb(int y, byte[] buffer)
	{
		if (precision == 8)
		{
			RGB24Image rgbImage = (RGB24Image)image;
			int offset = getBoundsX1() * 3;
			int x = 0;
			int k = getBoundsWidth();
			while (k > 0)
			{
				rgbImage.putSample(RGB24Image.INDEX_RED, x, y, buffer[offset++]);
				rgbImage.putSample(RGB24Image.INDEX_GREEN, x, y, buffer[offset++]);
				rgbImage.putSample(RGB24Image.INDEX_BLUE, x, y, buffer[offset++]);
				x++;
				k--;
			}
		}
		else
		if (precision == 16)
		{
			RGB48Image rgbImage = (RGB48Image)image;
			int offset = getBoundsX1() * 6;
			int x = 0;
			int k = getBoundsWidth();
			while (k > 0)
			{
				int red = (buffer[offset++] & 0xff) << 8;
				red |= buffer[offset++] & 0xff;
				rgbImage.putSample(RGB24Image.INDEX_RED, x, y, red);

				int green = (buffer[offset++] & 0xff) << 8;
				green |= buffer[offset++] & 0xff;
				rgbImage.putSample(RGB24Image.INDEX_GREEN, x, y, green);
	
				int blue = (buffer[offset++] & 0xff) << 8;
				blue |= buffer[offset++] & 0xff;
				rgbImage.putSample(RGB24Image.INDEX_BLUE, x, y, blue);
	
				x++;
				k--;
			}
		}
	}

	private void storeNonInterlacedRgbAlpha(int y, byte[] buffer)
	{
		switch(precision)
		{
			case(8):
			{
				RGB24Image rgbImage = (RGB24Image)image;
				int offset = getBoundsX1() * 3;
				int x = 0;
				int k = getBoundsWidth();
				while (k > 0)
				{
					rgbImage.putSample(RGB24Image.INDEX_RED, x, y, buffer[offset++]);
					rgbImage.putSample(RGB24Image.INDEX_GREEN, x, y, buffer[offset++]);
					rgbImage.putSample(RGB24Image.INDEX_BLUE, x, y, buffer[offset++]);
					offset++; // skip alpha; TODO: store in TransparencyInformation object
					x++;
					k--;
				}
				break;
			}
			case(16):
			{
				RGB48Image rgbImage = (RGB48Image)image;
				int offset = getBoundsX1() * 8;
				int x = 0;
				int k = getBoundsWidth();
				while (k > 0)
				{
					int red = (buffer[offset++] & 0xff) << 8;
					red |= buffer[offset++] & 0xff;
					rgbImage.putSample(RGB24Image.INDEX_RED, x, y, red);
		
					int green = (buffer[offset++] & 0xff) << 8;
					green |= buffer[offset++] & 0xff;
					rgbImage.putSample(RGB24Image.INDEX_GREEN, x, y, green);
		
					int blue = (buffer[offset++] & 0xff) << 8;
					blue |= buffer[offset++] & 0xff;
					rgbImage.putSample(RGB24Image.INDEX_BLUE, x, y, blue);
		
					offset += 2; // skip alpha; TODO: store in TransparencyInformation object
					x++;
					k--;
				}
				break;
			}
		}
	}

	public String suggestFileExtension(PixelImage image)
	{
		return ".png";
	}
}