File: Image.java

package info (click to toggle)
pdftk 1.41-3
  • links: PTS
  • area: main
  • in suites: lenny
  • size: 6,416 kB
  • ctags: 10,545
  • sloc: java: 73,698; cpp: 4,180; makefile: 294
file content (1975 lines) | stat: -rw-r--r-- 51,522 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
/*
 * $Id: Image.java,v 1.108 2005/10/06 10:32:48 psoares33 Exp $
 * $Name:  $
 *
 * Copyright 1999, 2000, 2001, 2002 by Bruno Lowagie.
 *
 * The contents of this file are subject to the Mozilla Public License Version 1.1
 * (the "License"); you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the License.
 *
 * The Original Code is 'iText, a free JAVA-PDF library'.
 *
 * The Initial Developer of the Original Code is Bruno Lowagie. Portions created by
 * the Initial Developer are Copyright (C) 1999, 2000, 2001, 2002 by Bruno Lowagie.
 * All Rights Reserved.
 * Co-Developer of the code is Paulo Soares. Portions created by the Co-Developer
 * are Copyright (C) 2000, 2001, 2002 by Paulo Soares. All Rights Reserved.
 *
 * Contributor(s): all the names of the contributors are added in the source code
 * where applicable.
 *
 * Alternatively, the contents of this file may be used under the terms of the
 * LGPL license (the "GNU LIBRARY GENERAL PUBLIC LICENSE"), in which case the
 * provisions of LGPL are applicable instead of those above.  If you wish to
 * allow use of your version of this file only under the terms of the LGPL
 * License and not to allow others to use your version of this file under
 * the MPL, indicate your decision by deleting the provisions above and
 * replace them with the notice and other provisions required by the LGPL.
 * If you do not delete the provisions above, a recipient may use your version
 * of this file under either the MPL or the GNU LIBRARY GENERAL PUBLIC LICENSE.
 *
 * This library is free software; you can redistribute it and/or modify it
 * under the terms of the MPL as stated above or under the terms of the GNU
 * Library General Public License as published by the Free Software Foundation;
 * either version 2 of the License, or any later version.
 *
 * This library is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU Library general Public License for more
 * details.
 *
 * If you didn't download this code from the following link, you should check if
 * you aren't using an obsolete version:
 * http://www.lowagie.com/iText/
 */

package com.lowagie.text;

import java.io.File;
import java.io.InputStream;
import java.io.IOException;
import java.net.URL;
import java.net.MalformedURLException;
import java.util.Properties;
import java.util.Set;
import java.util.ArrayList;
import java.awt.color.ICC_Profile;
import com.lowagie.text.pdf.PdfTemplate;
import com.lowagie.text.pdf.codec.CCITTG4Encoder;
import java.lang.reflect.Constructor;
import com.lowagie.text.pdf.RandomAccessFileOrArray;
import com.lowagie.text.pdf.PdfDictionary;
import com.lowagie.text.pdf.codec.GifImage;
import com.lowagie.text.pdf.codec.PngImage;
import com.lowagie.text.pdf.codec.TiffImage;
import com.lowagie.text.pdf.codec.BmpImage;
import com.lowagie.text.pdf.PdfOCG;
import com.lowagie.text.pdf.PdfObject;
import com.lowagie.text.pdf.PdfName;
import com.lowagie.text.pdf.PdfArray;

/**
 * An <CODE>Image</CODE> is the representation of a graphic element (JPEG, PNG
 * or GIF) that has to be inserted into the document
 * 
 * @see Element
 * @see Rectangle
 */

public abstract class Image extends Rectangle implements Element,
		MarkupAttributes {

	// static membervariables

	/** this is a kind of image alignment. */
	public static final int DEFAULT = 0;

	/** this is a kind of image alignment. */
	public static final int RIGHT = 2;

	/** this is a kind of image alignment. */
	public static final int LEFT = 0;

	/** this is a kind of image alignment. */
	public static final int MIDDLE = 1;

	/** this is a kind of image alignment. */
	public static final int TEXTWRAP = 4;

	/** this is a kind of image alignment. */
	public static final int UNDERLYING = 8;

	/** This represents a coordinate in the transformation matrix. */
	public static final int AX = 0;

	/** This represents a coordinate in the transformation matrix. */
	public static final int AY = 1;

	/** This represents a coordinate in the transformation matrix. */
	public static final int BX = 2;

	/** This represents a coordinate in the transformation matrix. */
	public static final int BY = 3;

	/** This represents a coordinate in the transformation matrix. */
	public static final int CX = 4;

	/** This represents a coordinate in the transformation matrix. */
	public static final int CY = 5;

	/** This represents a coordinate in the transformation matrix. */
	public static final int DX = 6;

	/** This represents a coordinate in the transformation matrix. */
	public static final int DY = 7;

	/** type of image */
	public static final int ORIGINAL_NONE = 0;

	/** type of image */
	public static final int ORIGINAL_JPEG = 1;

	/** type of image */
	public static final int ORIGINAL_PNG = 2;

	/** type of image */
	public static final int ORIGINAL_GIF = 3;

	/** type of image */
	public static final int ORIGINAL_BMP = 4;

	/** type of image */
	public static final int ORIGINAL_TIFF = 5;

	/** type of image */
	public static final int ORIGINAL_WMF = 6;

	/** type of image */
    public static final int ORIGINAL_PS = 7;

	/** Image color inversion */
	protected boolean invert = false;

	/** The imagetype. */
	protected int type;

	/** The URL of the image. */
	protected URL url;

	/** The raw data of the image. */
	protected byte rawData[];

	/** The template to be treated as an image. */
	protected PdfTemplate template[] = new PdfTemplate[1];

	/** The alignment of the Image. */
	protected int alignment;

	/** Text that can be shown instead of the image. */
	protected String alt;

	/** This is the absolute X-position of the image. */
	protected float absoluteX = Float.NaN;

	/** This is the absolute Y-position of the image. */
	protected float absoluteY = Float.NaN;

	/** This is the width of the image without rotation. */
	protected float plainWidth;

	/** This is the width of the image without rotation. */
	protected float plainHeight;

	/** This is the scaled width of the image taking rotation into account. */
	protected float scaledWidth;

	/** This is the original height of the image taking rotation into account. */
	protected float scaledHeight;

	/** This is the rotation of the image. */
	protected float rotation;

	/** this is the colorspace of a jpeg-image. */
	protected int colorspace = -1;

	/**
	 * this is the bits per component of the raw image. It also flags a CCITT
	 * image.
	 */
	protected int bpc = 1;

	/** this is the transparency information of the raw image */
	protected int transparency[];

	// for the moment these variables are only used for Images in class Table
	// code contributed by Pelikan Stephan
	/** the indentation to the left. */
	protected float indentationLeft = 0;

	/** the indentation to the right. */
	protected float indentationRight = 0;

	// serial stamping

	protected Long mySerialId = getSerialId();

	static long serialId = 0;

	/** Holds value of property dpiX. */
	protected int dpiX = 0;

	/** Holds value of property dpiY. */
	protected int dpiY = 0;

	protected boolean mask = false;

	protected Image imageMask;

	/** Holds value of property interpolation. */
	protected boolean interpolation;

	/** if the annotation is not null the image will be clickable. */
	protected Annotation annotation = null;

	/** Contains extra markupAttributes */
	protected Properties markupAttributes;

	/** ICC Profile attached */
	protected ICC_Profile profile = null;

	/** Holds value of property deflated. */
	protected boolean deflated = false;

	private PdfDictionary additional = null;

	/** Holds value of property smask. */
	private boolean smask;

	/** Holds value of property XYRatio. */
	private float XYRatio = 0;

	/** Holds value of property originalType. */
	protected int originalType = ORIGINAL_NONE;

	/** Holds value of property originalData. */
	protected byte[] originalData;

	/** The spacing before the image. */
	protected float spacingBefore;

	/** The spacing after the image. */
	protected float spacingAfter;

	/**
	 * Holds value of property widthPercentage.
	 */
	private float widthPercentage = 100;

	protected PdfOCG layer;

    /**
     * Holds value of property initialRotation.
     */
    private float initialRotation;
    
	// constructors

	/**
	 * Constructs an <CODE>Image</CODE> -object, using an <VAR>url </VAR>.
	 * 
	 * @param url
	 *            the <CODE>URL</CODE> where the image can be found.
	 */

	public Image(URL url) {
		super(0, 0);
		this.url = url;
		this.alignment = DEFAULT;
		rotation = 0;
	}

	/**
	 * Constructs an <CODE>Image</CODE> -object, using an <VAR>url </VAR>.
	 * 
	 * @param image
	 *            another Image object.
	 */

	protected Image(Image image) {
		super(image);
		this.type = image.type;
		this.url = image.url;
		this.alignment = image.alignment;
		this.alt = image.alt;
		this.absoluteX = image.absoluteX;
		this.absoluteY = image.absoluteY;
		this.plainWidth = image.plainWidth;
		this.plainHeight = image.plainHeight;
		this.scaledWidth = image.scaledWidth;
		this.scaledHeight = image.scaledHeight;
		this.rotation = image.rotation;
		this.colorspace = image.colorspace;
		this.rawData = image.rawData;
		this.template = image.template;
		this.bpc = image.bpc;
		this.transparency = image.transparency;
		this.mySerialId = image.mySerialId;
		this.invert = image.invert;
		this.dpiX = image.dpiX;
		this.dpiY = image.dpiY;
		this.mask = image.mask;
		this.imageMask = image.imageMask;
		this.interpolation = image.interpolation;
		this.annotation = image.annotation;
		this.markupAttributes = image.markupAttributes;
		this.profile = image.profile;
		this.deflated = image.deflated;
		this.additional = image.additional;
		this.smask = image.smask;
		this.XYRatio = image.XYRatio;
		this.originalData = image.originalData;
		this.originalType = image.originalType;
		this.spacingAfter = image.spacingAfter;
		this.spacingBefore = image.spacingBefore;
		this.widthPercentage = image.widthPercentage;
		this.layer = image.layer;
        this.initialRotation = image.initialRotation;
	}

	/**
	 * gets an instance of an Image
	 * 
	 * @param image
	 *            an Image object
	 * @return a new Image object
	 */

	public static Image getInstance(Image image) {
		if (image == null)
			return null;
		try {
			Class cs = image.getClass();
			Constructor constructor = cs
					.getDeclaredConstructor(new Class[] { Image.class });
			return (Image) constructor.newInstance(new Object[] { image });
		} catch (Exception e) {
			throw new ExceptionConverter(e);
		}
	}

	/**
	 * Gets an instance of an Image.
	 * 
	 * @param url
	 *            an URL
	 * @return an Image
	 * @throws BadElementException
	 * @throws MalformedURLException
	 * @throws IOException
	 */

	public static Image getInstance(URL url) throws BadElementException,
			MalformedURLException, IOException {
		InputStream is = null;
		try {
			is = url.openStream();
			int c1 = is.read();
			int c2 = is.read();
			int c3 = is.read();
			int c4 = is.read();
			is.close();

			is = null;
			if (c1 == 'G' && c2 == 'I' && c3 == 'F') {
				GifImage gif = new GifImage(url);
				Image img = gif.getImage(1);
				return img;
			}
			if (c1 == 0xFF && c2 == 0xD8) {
				return new Jpeg(url);
			}
			if (c1 == PngImage.PNGID[0] && c2 == PngImage.PNGID[1]
					&& c3 == PngImage.PNGID[2] && c4 == PngImage.PNGID[3]) {
				return PngImage.getImage(url);
			}
            if (c1 == '%' && c2 == '!' && c3 == 'P' && c4 == 'S') {
               return new ImgPostscript(url);
            }
			if (c1 == 0xD7 && c2 == 0xCD) {
				return new ImgWMF(url);
			}
			if (c1 == 'B' && c2 == 'M') {
				return  BmpImage.getImage(url);
			}
			if ((c1 == 'M' && c2 == 'M' && c3 == 0 && c4 == 42)
					|| (c1 == 'I' && c2 == 'I' && c3 == 42 && c4 == 0)) {
				RandomAccessFileOrArray ra = null;
				try {
					if (url.getProtocol().equals("file")) {
						String file = url.getFile();
						ra = new RandomAccessFileOrArray(file);
					} else
						ra = new RandomAccessFileOrArray(url);
					Image img = TiffImage.getTiffImage(ra, 1);
					img.url = url;
					return img;
				} finally {
					if (ra != null)
						ra.close();
				}

			}
			throw new IOException(url.toString()
					+ " is not a recognized imageformat.");
		} finally {
			if (is != null) {
				is.close();
			}
		}
	}

	/**
	 * gets an instance of an Image
	 * 
	 * @param imgb
	 *            raw image date
	 * @return an Image object
	 * @throws BadElementException
	 * @throws MalformedURLException
	 * @throws IOException
	 */
	public static Image getInstance(byte imgb[]) throws BadElementException,
			MalformedURLException, IOException {
		InputStream is = null;
		try {
			is = new java.io.ByteArrayInputStream(imgb);
			int c1 = is.read();
			int c2 = is.read();
			int c3 = is.read();
			int c4 = is.read();
			is.close();

			is = null;
			if (c1 == 'G' && c2 == 'I' && c3 == 'F') {
				GifImage gif = new GifImage(imgb);
				return gif.getImage(1);
			}
			if (c1 == 0xFF && c2 == 0xD8) {
				return new Jpeg(imgb);
			}
			if (c1 == PngImage.PNGID[0] && c2 == PngImage.PNGID[1]
					&& c3 == PngImage.PNGID[2] && c4 == PngImage.PNGID[3]) {
				return PngImage.getImage(imgb);
			}
            if (c1 == '%' && c2 == '!' && c3 == 'P' && c4 == 'S') {
               return new ImgPostscript(imgb);
            }
			if (c1 == 0xD7 && c2 == 0xCD) {
				return new ImgWMF(imgb);
			}
			if (c1 == 'B' && c2 == 'M') {
				return BmpImage.getImage(imgb);
			}
			if ((c1 == 'M' && c2 == 'M' && c3 == 0 && c4 == 42)
					|| (c1 == 'I' && c2 == 'I' && c3 == 42 && c4 == 0)) {
				RandomAccessFileOrArray ra = null;
				try {
					ra = new RandomAccessFileOrArray(imgb);
					Image img = TiffImage.getTiffImage(ra, 1);
                    if (img.getOriginalData() == null)
                        img.setOriginalData(imgb);
					return img;
				} finally {
					if (ra != null)
						ra.close();
				}

			}
			throw new IOException(
					"The byte array is not a recognized imageformat.");
		} finally {
			if (is != null) {
				is.close();
			}
		}
	}

	/**
	 * Gets an instance of an Image from a java.awt.Image.
	 * 
	 * @param image
	 *            the <CODE>java.awt.Image</CODE> to convert
	 * @param color
	 *            if different from <CODE>null</CODE> the transparency pixels
	 *            are replaced by this color
	 * @param forceBW
	 *            if <CODE>true</CODE> the image is treated as black and white
	 * @return an object of type <CODE>ImgRaw</CODE>
	 * @throws BadElementException
	 *             on error
	 * @throws IOException
	 *             on error
	 */

	public static Image getInstance(java.awt.Image image, java.awt.Color color,
			boolean forceBW) throws BadElementException, IOException {
		java.awt.image.PixelGrabber pg = new java.awt.image.PixelGrabber(image,
				0, 0, -1, -1, true);
		try {
			pg.grabPixels();
		} catch (InterruptedException e) {
			throw new IOException(
					"java.awt.Image Interrupted waiting for pixels!");
		}
		if ((pg.getStatus() & java.awt.image.ImageObserver.ABORT) != 0) {
			throw new IOException("java.awt.Image fetch aborted or errored");
		}
		int w = pg.getWidth();
		int h = pg.getHeight();
		int[] pixels = (int[]) pg.getPixels();
		if (forceBW) {
			int byteWidth = (w / 8) + ((w & 7) != 0 ? 1 : 0);
			byte[] pixelsByte = new byte[byteWidth * h];

			int index = 0;
			int size = h * w;
			int transColor = 1;
			if (color != null) {
				transColor = (color.getRed() + color.getGreen()
						+ color.getBlue() < 384) ? 0 : 1;
			}
			int transparency[] = null;
			int cbyte = 0x80;
			int wMarker = 0;
			int currByte = 0;
			if (color != null) {
				for (int j = 0; j < size; j++) {
					int alpha = (pixels[j] >> 24) & 0xff;
					if (alpha < 250) {
						if (transColor == 1)
							currByte |= cbyte;
					} else {
						if ((pixels[j] & 0x888) != 0)
							currByte |= cbyte;
					}
					cbyte >>= 1;
					if (cbyte == 0 || wMarker + 1 >= w) {
						pixelsByte[index++] = (byte) currByte;
						cbyte = 0x80;
						currByte = 0;
					}
					++wMarker;
					if (wMarker >= w)
						wMarker = 0;
				}
			} else {
				for (int j = 0; j < size; j++) {
					if (transparency == null) {
						int alpha = (pixels[j] >> 24) & 0xff;
						if (alpha == 0) {
							transparency = new int[2];
							transparency[0] = transparency[1] = ((pixels[j] & 0x888) != 0) ? 1
									: 0;
						}
					}
					if ((pixels[j] & 0x888) != 0)
						currByte |= cbyte;
					cbyte >>= 1;
					if (cbyte == 0 || wMarker + 1 >= w) {
						pixelsByte[index++] = (byte) currByte;
						cbyte = 0x80;
						currByte = 0;
					}
					++wMarker;
					if (wMarker >= w)
						wMarker = 0;
				}
			}
			return Image.getInstance(w, h, 1, 1, pixelsByte, transparency);
		} else {
			byte[] pixelsByte = new byte[w * h * 3];
			byte[] smask = null;

			int index = 0;
			int size = h * w;
			int red = 255;
			int green = 255;
			int blue = 255;
			if (color != null) {
				red = color.getRed();
				green = color.getGreen();
				blue = color.getBlue();
			}
			int transparency[] = null;
			if (color != null) {
				for (int j = 0; j < size; j++) {
					int alpha = (pixels[j] >> 24) & 0xff;
					if (alpha < 250) {
						pixelsByte[index++] = (byte) red;
						pixelsByte[index++] = (byte) green;
						pixelsByte[index++] = (byte) blue;
					} else {
						pixelsByte[index++] = (byte) ((pixels[j] >> 16) & 0xff);
						pixelsByte[index++] = (byte) ((pixels[j] >> 8) & 0xff);
						pixelsByte[index++] = (byte) ((pixels[j]) & 0xff);
					}
				}
			} else {
				int transparentPixel = 0;
				smask = new byte[w * h];
				boolean shades = false;
				for (int j = 0; j < size; j++) {
					byte alpha = smask[j] = (byte) ((pixels[j] >> 24) & 0xff);
					/* bugfix by Chris Nokleberg */
					if (!shades) {
						if (alpha != 0 && alpha != -1) {
							shades = true;
						} else if (transparency == null) {
							if (alpha == 0) {
								transparentPixel = pixels[j] & 0xffffff;
								transparency = new int[6];
								transparency[0] = transparency[1] = (transparentPixel >> 16) & 0xff;
								transparency[2] = transparency[3] = (transparentPixel >> 8) & 0xff;
								transparency[4] = transparency[5] = transparentPixel & 0xff;
							}
						} else if ((pixels[j] & 0xffffff) != transparentPixel) {
							shades = true;
						}
					}
					pixelsByte[index++] = (byte) ((pixels[j] >> 16) & 0xff);
					pixelsByte[index++] = (byte) ((pixels[j] >> 8) & 0xff);
					pixelsByte[index++] = (byte) ((pixels[j]) & 0xff);
				}
				if (shades)
					transparency = null;
				else
					smask = null;
			}
			Image img = Image.getInstance(w, h, 3, 8, pixelsByte, transparency);
			if (smask != null) {
				Image sm = Image.getInstance(w, h, 1, 8, smask);
				try {
					sm.makeMask();
					img.setImageMask(sm);
				} catch (DocumentException de) {
					throw new ExceptionConverter(de);
				}
			}
			return img;
		}
	}

	/**
	 * Gets an instance of an Image from a java.awt.Image.
	 * 
	 * @param image
	 *            the <CODE>java.awt.Image</CODE> to convert
	 * @param color
	 *            if different from <CODE>null</CODE> the transparency pixels
	 *            are replaced by this color
	 * @return an object of type <CODE>ImgRaw</CODE>
	 * @throws BadElementException
	 *             on error
	 * @throws IOException
	 *             on error
	 */
	public static Image getInstance(java.awt.Image image, java.awt.Color color)
			throws BadElementException, IOException {
		return Image.getInstance(image, color, false);
	}

	/**
	 * Gets an instance of an Image.
	 * 
	 * @param filename
	 *            a filename
	 * @return an object of type <CODE>Gif</CODE>,<CODE>Jpeg</CODE> or
	 *         <CODE>Png</CODE>
	 * @throws BadElementException
	 * @throws MalformedURLException
	 * @throws IOException
	 */

	public static Image getInstance(String filename)
			throws BadElementException, MalformedURLException, IOException {
		return getInstance(toURL(filename));
	}

	/**
	 * Gets an instance of an Image in raw mode.
	 * 
	 * @param width
	 *            the width of the image in pixels
	 * @param height
	 *            the height of the image in pixels
	 * @param components
	 *            1,3 or 4 for GrayScale, RGB and CMYK
	 * @param data
	 *            the image data
	 * @param bpc
	 *            bits per component
	 * @return an object of type <CODE>ImgRaw</CODE>
	 * @throws BadElementException
	 *             on error
	 */

	public static Image getInstance(int width, int height, int components,
			int bpc, byte data[]) throws BadElementException {
		return Image.getInstance(width, height, components, bpc, data, null);
	}

	/**
	 * gets an instance of an Image
	 * 
	 * @param template
	 *            a PdfTemplate that has to be wrapped in an Image object
	 * @return an Image object
	 * @throws BadElementException
	 */
	public static Image getInstance(PdfTemplate template)
			throws BadElementException {
		return new ImgTemplate(template);
	}

	/**
	 * Creates an Image with CCITT G3 or G4 compression. It assumes that the
	 * data bytes are already compressed.
	 * 
	 * @param width
	 *            the exact width of the image
	 * @param height
	 *            the exact height of the image
	 * @param reverseBits
	 *            reverses the bits in <code>data</code>. Bit 0 is swapped
	 *            with bit 7 and so on
	 * @param typeCCITT
	 *            the type of compression in <code>data</code>. It can be
	 *            CCITTG4, CCITTG31D, CCITTG32D
	 * @param parameters
	 *            parameters associated with this stream. Possible values are
	 *            CCITT_BLACKIS1, CCITT_ENCODEDBYTEALIGN, CCITT_ENDOFLINE and
	 *            CCITT_ENDOFBLOCK or a combination of them
	 * @param data
	 *            the image data
	 * @return an Image object
	 * @throws BadElementException
	 *             on error
	 */
	public static Image getInstance(int width, int height, boolean reverseBits,
			int typeCCITT, int parameters, byte[] data)
			throws BadElementException {
		return Image.getInstance(width, height, reverseBits, typeCCITT,
				parameters, data, null);
	}

	/**
	 * Creates an Image with CCITT G3 or G4 compression. It assumes that the
	 * data bytes are already compressed.
	 * 
	 * @param width
	 *            the exact width of the image
	 * @param height
	 *            the exact height of the image
	 * @param reverseBits
	 *            reverses the bits in <code>data</code>. Bit 0 is swapped
	 *            with bit 7 and so on
	 * @param typeCCITT
	 *            the type of compression in <code>data</code>. It can be
	 *            CCITTG4, CCITTG31D, CCITTG32D
	 * @param parameters
	 *            parameters associated with this stream. Possible values are
	 *            CCITT_BLACKIS1, CCITT_ENCODEDBYTEALIGN, CCITT_ENDOFLINE and
	 *            CCITT_ENDOFBLOCK or a combination of them
	 * @param data
	 *            the image data
	 * @param transparency
	 *            transparency information in the Mask format of the image
	 *            dictionary
	 * @return an Image object
	 * @throws BadElementException
	 *             on error
	 */
	public static Image getInstance(int width, int height, boolean reverseBits,
			int typeCCITT, int parameters, byte[] data, int transparency[])
			throws BadElementException {
		if (transparency != null && transparency.length != 2)
			throw new BadElementException(
					"Transparency length must be equal to 2 with CCITT images");
		Image img = new ImgCCITT(width, height, reverseBits, typeCCITT,
				parameters, data);
		img.transparency = transparency;
		return img;
	}

	/**
	 * Gets an instance of an Image in raw mode.
	 * 
	 * @param width
	 *            the width of the image in pixels
	 * @param height
	 *            the height of the image in pixels
	 * @param components
	 *            1,3 or 4 for GrayScale, RGB and CMYK
	 * @param data
	 *            the image data
	 * @param bpc
	 *            bits per component
	 * @param transparency
	 *            transparency information in the Mask format of the image
	 *            dictionary
	 * @return an object of type <CODE>ImgRaw</CODE>
	 * @throws BadElementException
	 *             on error
	 */

	public static Image getInstance(int width, int height, int components,
			int bpc, byte data[], int transparency[])
			throws BadElementException {
		if (transparency != null && transparency.length != components * 2)
			throw new BadElementException(
					"Transparency length must be equal to (componentes * 2)");
		if (components == 1 && bpc == 1) {
			byte g4[] = CCITTG4Encoder.compress(data, width, height);
			return Image.getInstance(width, height, false, Image.CCITTG4,
					Image.CCITT_BLACKIS1, g4, transparency);
		}
		Image img = new ImgRaw(width, height, components, bpc, data);
		img.transparency = transparency;
		return img;
	}

	/**
	 * Returns an <CODE>Image</CODE> that has been constructed taking in
	 * account the value of some <VAR>attributes </VAR>.
	 * 
	 * @param attributes
	 *            Some attributes
	 * @return an <CODE>Image</CODE>
	 * @throws BadElementException
	 * @throws MalformedURLException
	 * @throws IOException
	 */

	public static Image getInstance(Properties attributes)
			throws BadElementException, MalformedURLException, IOException {
		String value = (String) attributes.remove(ElementTags.URL);
		if (value == null)
			throw new MalformedURLException("The URL of the image is missing.");
		Image image = Image.getInstance(value);
		int align = 0;
		if ((value = (String) attributes.remove(ElementTags.ALIGN)) != null) {
			if (ElementTags.ALIGN_LEFT.equalsIgnoreCase(value))
				align |= Image.LEFT;
			else if (ElementTags.ALIGN_RIGHT.equalsIgnoreCase(value))
				align |= Image.RIGHT;
			else if (ElementTags.ALIGN_MIDDLE.equalsIgnoreCase(value))
				align |= Image.MIDDLE;
		}
		if ((value = (String) attributes.remove(ElementTags.UNDERLYING)) != null) {
			if (new Boolean(value).booleanValue())
				align |= Image.UNDERLYING;
		}
		if ((value = (String) attributes.remove(ElementTags.TEXTWRAP)) != null) {
			if (new Boolean(value).booleanValue())
				align |= Image.TEXTWRAP;
		}
		image.setAlignment(align);
		if ((value = (String) attributes.remove(ElementTags.ALT)) != null) {
			image.setAlt(value);
		}
		String x;
		String y;
		if (((x = (String) attributes.remove(ElementTags.ABSOLUTEX)) != null)
				&& ((y = (String) attributes.remove(ElementTags.ABSOLUTEY)) != null)) {
			image.setAbsolutePosition(Float.valueOf(x + "f").floatValue(),
					Float.valueOf(y + "f").floatValue());
		}
		if ((value = (String) attributes.remove(ElementTags.PLAINWIDTH)) != null) {
			image.scaleAbsoluteWidth(Float.valueOf(value + "f").floatValue());
		}
		if ((value = (String) attributes.remove(ElementTags.PLAINHEIGHT)) != null) {
			image.scaleAbsoluteHeight(Float.valueOf(value + "f").floatValue());
		}
		if ((value = (String) attributes.remove(ElementTags.ROTATION)) != null) {
			image.setRotation(Float.valueOf(value + "f").floatValue());
		}
		if (attributes.size() > 0)
			image.setMarkupAttributes(attributes);
		return image;
	}

	// methods to set information

	/**
	 * Sets the alignment for the image.
	 * 
	 * @param alignment
	 *            the alignment
	 */

	public void setAlignment(int alignment) {
		this.alignment = alignment;
	}

	/**
	 * Sets the alternative information for the image.
	 * 
	 * @param alt
	 *            the alternative information
	 */

	public void setAlt(String alt) {
		this.alt = alt;
	}

	/**
	 * Sets the absolute position of the <CODE>Image</CODE>.
	 * 
	 * @param absoluteX
	 * @param absoluteY
	 */

	public void setAbsolutePosition(float absoluteX, float absoluteY) {
		this.absoluteX = absoluteX;
		this.absoluteY = absoluteY;
	}

	/**
	 * Scale the image to an absolute width and an absolute height.
	 * 
	 * @param newWidth
	 *            the new width
	 * @param newHeight
	 *            the new height
	 */

	public void scaleAbsolute(float newWidth, float newHeight) {
		plainWidth = newWidth;
		plainHeight = newHeight;
		float[] matrix = matrix();
		scaledWidth = matrix[DX] - matrix[CX];
		scaledHeight = matrix[DY] - matrix[CY];
	}

	/**
	 * Scale the image to an absolute width.
	 * 
	 * @param newWidth
	 *            the new width
	 */

	public void scaleAbsoluteWidth(float newWidth) {
		plainWidth = newWidth;
		float[] matrix = matrix();
		scaledWidth = matrix[DX] - matrix[CX];
		scaledHeight = matrix[DY] - matrix[CY];
	}

	/**
	 * Scale the image to an absolute height.
	 * 
	 * @param newHeight
	 *            the new height
	 */

	public void scaleAbsoluteHeight(float newHeight) {
		plainHeight = newHeight;
		float[] matrix = matrix();
		scaledWidth = matrix[DX] - matrix[CX];
		scaledHeight = matrix[DY] - matrix[CY];
	}

	/**
	 * Scale the image to a certain percentage.
	 * 
	 * @param percent
	 *            the scaling percentage
	 */

	public void scalePercent(float percent) {
		scalePercent(percent, percent);
	}

	/**
	 * Scale the width and height of an image to a certain percentage.
	 * 
	 * @param percentX
	 *            the scaling percentage of the width
	 * @param percentY
	 *            the scaling percentage of the height
	 */

	public void scalePercent(float percentX, float percentY) {
		plainWidth = (width() * percentX) / 100f;
		plainHeight = (height() * percentY) / 100f;
		float[] matrix = matrix();
		scaledWidth = matrix[DX] - matrix[CX];
		scaledHeight = matrix[DY] - matrix[CY];
	}

	/**
	 * Scales the image so that it fits a certain width and height.
	 * 
	 * @param fitWidth
	 *            the width to fit
	 * @param fitHeight
	 *            the height to fit
	 */

	public void scaleToFit(float fitWidth, float fitHeight) {
        scalePercent(100);
		float percentX = (fitWidth * 100) / scaledWidth();
		float percentY = (fitHeight * 100) / scaledHeight();
		scalePercent(percentX < percentY ? percentX : percentY);
	}

	/**
	 * Sets the rotation of the image in radians.
	 * 
	 * @param r
	 *            rotation in radians
	 */

	public void setRotation(float r) {
		double d = Math.PI; //__IDS__
		rotation = (float) ((r + initialRotation) % (2.0 * d)); //__IDS__
		if (rotation < 0) {
			rotation += 2.0 * d; //__IDS__
		}
		float[] matrix = matrix();
		scaledWidth = matrix[DX] - matrix[CX];
		scaledHeight = matrix[DY] - matrix[CY];
	}

	/**
	 * Sets the rotation of the image in degrees.
	 * 
	 * @param deg
	 *            rotation in degrees
	 */

	public void setRotationDegrees(float deg) {
		double d = Math.PI; //__IDS__
		setRotation(deg / 180 * (float) d); //__IDS__
	}

	/**
	 * Sets the annotation of this Image.
	 * 
	 * @param annotation
	 *            the annotation
	 */

	public void setAnnotation(Annotation annotation) {
		this.annotation = annotation;
	}

	/**
	 * Gets the annotation.
	 * 
	 * @return the annotation that is linked to this image
	 */

	public Annotation annotation() {
		return annotation;
	}

	// methods to retrieve information

	/**
	 * Gets the bpc for the image.
	 * <P>
	 * Remark: this only makes sense for Images of the type <CODE>RawImage
	 * </CODE>.
	 * 
	 * @return a bpc value
	 */

	public int bpc() {
		return bpc;
	}

	/**
	 * Gets the raw data for the image.
	 * <P>
	 * Remark: this only makes sense for Images of the type <CODE>RawImage
	 * </CODE>.
	 * 
	 * @return the raw data
	 */

	public byte[] rawData() {
		return rawData;
	}

	/**
	 * Gets the template to be used as an image.
	 * <P>
	 * Remark: this only makes sense for Images of the type <CODE>ImgTemplate
	 * </CODE>.
	 * 
	 * @return the template
	 */

	public PdfTemplate templateData() {
		return template[0];
	}

	/**
	 * Sets data from a PdfTemplate
	 * 
	 * @param template
	 *            the template with the content
	 */
	public void setTemplateData(PdfTemplate template) {
		this.template[0] = template;
	}

	/**
	 * Checks if the <CODE>Images</CODE> has to be added at an absolute
	 * position.
	 * 
	 * @return a boolean
	 */

	public boolean hasAbsolutePosition() {
		return !Float.isNaN(absoluteY);
	}

	/**
	 * Checks if the <CODE>Images</CODE> has to be added at an absolute X
	 * position.
	 * 
	 * @return a boolean
	 */

	public boolean hasAbsoluteX() {
		return !Float.isNaN(absoluteX);
	}

	/**
	 * Returns the absolute X position.
	 * 
	 * @return a position
	 */

	public float absoluteX() {
		return absoluteX;
	}

	/**
	 * Returns the absolute Y position.
	 * 
	 * @return a position
	 */

	public float absoluteY() {
		return absoluteY;
	}

	/**
	 * Returns the type.
	 * 
	 * @return a type
	 */

	public int type() {
		return type;
	}

	/**
	 * Returns <CODE>true</CODE> if the image is a <CODE>Jpeg</CODE>
	 * -object.
	 * 
	 * @return a <CODE>boolean</CODE>
	 */

	public boolean isJpeg() {
		return type == JPEG;
	}

	/**
	 * Returns <CODE>true</CODE> if the image is a <CODE>ImgRaw</CODE>
	 * -object.
	 * 
	 * @return a <CODE>boolean</CODE>
	 */

	public boolean isImgRaw() {
		return type == IMGRAW;
	}

	/**
	 * Returns <CODE>true</CODE> if the image is an <CODE>ImgTemplate</CODE>
	 * -object.
	 * 
	 * @return a <CODE>boolean</CODE>
	 */

	public boolean isImgTemplate() {
		return type == IMGTEMPLATE;
	}

	/**
	 * Gets the <CODE>String</CODE> -representation of the reference to the
	 * image.
	 * 
	 * @return a <CODE>String</CODE>
	 */

	public URL url() {
		return url;
	}

	/**
	 * Gets the alignment for the image.
	 * 
	 * @return a value
	 */

	public int alignment() {
		return alignment;
	}

	/**
	 * Gets the alternative text for the image.
	 * 
	 * @return a <CODE>String</CODE>
	 */

	public String alt() {
		return alt;
	}

	/**
	 * Gets the scaled width of the image.
	 * 
	 * @return a value
	 */

	public float scaledWidth() {
		return scaledWidth;
	}

	/**
	 * Gets the scaled height of the image.
	 * 
	 * @return a value
	 */

	public float scaledHeight() {
		return scaledHeight;
	}

	/**
	 * Gets the colorspace for the image.
	 * <P>
	 * Remark: this only makes sense for Images of the type <CODE>Jpeg</CODE>.
	 * 
	 * @return a colorspace value
	 */

	public int colorspace() {
		return colorspace;
	}

	/**
	 * Returns the transformation matrix of the image.
	 * 
	 * @return an array [AX, AY, BX, BY, CX, CY, DX, DY]
	 */

	public float[] matrix() {
		float[] matrix = new float[8];
		float cosX = (float) Math.cos(rotation);
		float sinX = (float) Math.sin(rotation);
		matrix[AX] = plainWidth * cosX;
		matrix[AY] = plainWidth * sinX;
		matrix[BX] = (-plainHeight) * sinX;
		matrix[BY] = plainHeight * cosX;
		if (rotation < Math.PI / 2f) {
			matrix[CX] = matrix[BX];
			matrix[CY] = 0;
			matrix[DX] = matrix[AX];
			matrix[DY] = matrix[AY] + matrix[BY];
		} else if (rotation < Math.PI) {
			matrix[CX] = matrix[AX] + matrix[BX];
			matrix[CY] = matrix[BY];
			matrix[DX] = 0;
			matrix[DY] = matrix[AY];
		} else if (rotation < Math.PI * 1.5f) {
			matrix[CX] = matrix[AX];
			matrix[CY] = matrix[AY] + matrix[BY];
			matrix[DX] = matrix[BX];
			matrix[DY] = 0;
		} else {
			matrix[CX] = 0;
			matrix[CY] = matrix[AY];
			matrix[DX] = matrix[AX] + matrix[BX];
			matrix[DY] = matrix[BY];
		}
		return matrix;
	}

	/**
	 * This method is an alternative for the <CODE>InputStream.skip()</CODE>
	 * -method that doesn't seem to work properly for big values of <CODE>size
	 * </CODE>.
	 * 
	 * @param is
	 *            the <CODE>InputStream</CODE>
	 * @param size
	 *            the number of bytes to skip
	 * @throws IOException
	 */

	static public void skip(InputStream is, int size) throws IOException {
        long n;
		while (size > 0) {
            n = is.skip(size);
            if (n <= 0)
                break;
			size -= n;
		}
	}

    private static String excUri = " <>#%\"{}[]|\\\u005E\u0060";
    private static String[] excUriEsc = {"%20", "%3C", "%3E", "%23", "%25", "%22", "%7B", "%7D", "%5B", "%5D", "%7C", "%5C", "%5E", "%60"};
	/**
	 * This method makes a valid URL from a given filename.
	 * <P>
	 * This method makes the conversion of this library from the JAVA 2 platform
	 * to a JDK1.1.x-version easier.
	 * 
	 * @param filename
	 *            a given filename
	 * @return a valid URL
	 * @throws MalformedURLException
	 */

	public static URL toURL(String filename) throws MalformedURLException {
		if (filename.startsWith("file:/") || filename.startsWith("http://")
				|| filename.startsWith("https://")
				|| filename.startsWith("jar:")) {
			return new URL(filename);
		}
		File f = new File(filename);
		String path = f.getAbsolutePath();
		if (File.separatorChar != '/') {
			path = path.replace(File.separatorChar, '/');
		}
		if (!path.startsWith("/")) {
			path = "/" + path;
		}
		if (!path.endsWith("/") && f.isDirectory()) {
			path = path + "/";
		}
        char[] t = path.toCharArray();
        StringBuffer sb = new StringBuffer();
        for (int k = 0; k < t.length; ++k) {
            char c = t[k];
            int a = excUri.indexOf(c);
            if (a >= 0)
                sb.append(excUriEsc[a]);
            else
                sb.append(c);
        }
		return new URL("file", "", sb.toString());
	}

	/**
	 * Returns the transparency.
	 * 
	 * @return the transparency values
	 */

	public int[] getTransparency() {
		return transparency;
	}

	/**
	 * Sets the transparency values
	 * 
	 * @param transparency
	 *            the transparency values
	 */
	public void setTransparency(int transparency[]) {
		this.transparency = transparency;
	}

	/**
	 * Checks if a given tag corresponds with this object.
	 * 
	 * @param tag
	 *            the given tag
	 * @return true if the tag corresponds
	 */

	public static boolean isTag(String tag) {
		return ElementTags.IMAGE.equals(tag);
	}

	/**
	 * Gets the plain width of the image.
	 * 
	 * @return a value
	 */

	public float plainWidth() {
		return plainWidth;
	}

	/**
	 * Gets the plain height of the image.
	 * 
	 * @return a value
	 */

	public float plainHeight() {
		return plainHeight;
	}

	static protected synchronized Long getSerialId() {
		++serialId;
		return new Long(serialId);
	}

	/**
	 * Returns a serial id for the Image (reuse the same image more than once)
	 * 
	 * @return a serialId
	 */
	public Long getMySerialId() {
		return mySerialId;
	}

	/**
	 * Gets the dots-per-inch in the X direction. Returns 0 if not available.
	 * 
	 * @return the dots-per-inch in the X direction
	 */
	public int getDpiX() {
		return dpiX;
	}

	/**
	 * Gets the dots-per-inch in the Y direction. Returns 0 if not available.
	 * 
	 * @return the dots-per-inch in the Y direction
	 */
	public int getDpiY() {
		return dpiY;
	}

	/**
	 * Sets the dots per inch value
	 * 
	 * @param dpiX
	 *            dpi for x coordinates
	 * @param dpiY
	 *            dpi for y coordinates
	 */
	public void setDpi(int dpiX, int dpiY) {
		this.dpiX = dpiX;
		this.dpiY = dpiY;
	}

	/**
	 * Returns <CODE>true</CODE> if this <CODE>Image</CODE> has the
	 * requisites to be a mask.
	 * 
	 * @return <CODE>true</CODE> if this <CODE>Image</CODE> can be a mask
	 */
	public boolean isMaskCandidate() {
		if (type == IMGRAW) {
			if (bpc > 0xff)
				return true;
		}
		return colorspace == 1;
	}

	/**
	 * Make this <CODE>Image</CODE> a mask.
	 * 
	 * @throws DocumentException
	 *             if this <CODE>Image</CODE> can not be a mask
	 */
	public void makeMask() throws DocumentException {
		if (!isMaskCandidate())
			throw new DocumentException("This image can not be an image mask.");
		mask = true;
	}

	/**
	 * Sets the explicit masking.
	 * 
	 * @param mask
	 *            the mask to be applied
	 * @throws DocumentException
	 *             on error
	 */
	public void setImageMask(Image mask) throws DocumentException {
		if (this.mask)
			throw new DocumentException(
					"An image mask cannot contain another image mask.");
		if (!mask.mask)
			throw new DocumentException(
					"The image mask is not a mask. Did you do makeMask()?");
		imageMask = mask;
		smask = (mask.bpc > 1 && mask.bpc <= 8);
	}

	/**
	 * Gets the explicit masking.
	 * 
	 * @return the explicit masking
	 */
	public Image getImageMask() {
		return imageMask;
	}

	/**
	 * Returns <CODE>true</CODE> if this <CODE>Image</CODE> is a mask.
	 * 
	 * @return <CODE>true</CODE> if this <CODE>Image</CODE> is a mask
	 */
	public boolean isMask() {
		return mask;
	}

	/**
	 * Inverts the meaning of the bits of a mask.
	 * 
	 * @param invert
	 *            <CODE>true</CODE> to invert the meaning of the bits of a
	 *            mask
	 */
	public void setInvertMask(boolean invert) {
		this.invert = invert;
	}

	/**
	 * Returns <CODE>true</CODE> if the bits are to be inverted in the mask.
	 * 
	 * @return <CODE>true</CODE> if the bits are to be inverted in the mask
	 */
	public boolean isInvertMask() {
		return invert;
	}

	/**
	 * Getter for the inverted value
	 * 
	 * @return true if the image is inverted
	 */
	public boolean isInverted() {
		return invert;
	}

	/**
	 * Sets inverted true or false
	 * 
	 * @param invert
	 *            true or false
	 */
	public void setInverted(boolean invert) {
		this.invert = invert;
	}

	/**
	 * Getter for property interpolation.
	 * 
	 * @return Value of property interpolation.
	 */
	public boolean isInterpolation() {
		return interpolation;
	}

	/**
	 * Sets the image interpolation. Image interpolation attempts to produce a
	 * smooth transition between adjacent sample values.
	 * 
	 * @param interpolation
	 *            New value of property interpolation.
	 */
	public void setInterpolation(boolean interpolation) {
		this.interpolation = interpolation;
	}

	/**
	 * @see com.lowagie.text.MarkupAttributes#setMarkupAttribute(java.lang.String,
	 *      java.lang.String)
	 */
	public void setMarkupAttribute(String name, String value) {
		if (markupAttributes == null) markupAttributes = new Properties();
		markupAttributes.put(name, value);
	}

	/**
	 * @see com.lowagie.text.MarkupAttributes#setMarkupAttributes(java.util.Properties)
	 */
	public void setMarkupAttributes(Properties markupAttributes) {
		this.markupAttributes = markupAttributes;
	}

	/**
	 * @see com.lowagie.text.MarkupAttributes#getMarkupAttribute(java.lang.String)
	 */
	public String getMarkupAttribute(String name) {
		return (markupAttributes == null) ? null : String
				.valueOf(markupAttributes.get(name));
	}

	/**
	 * @see com.lowagie.text.MarkupAttributes#getMarkupAttributeNames()
	 */
	public Set getMarkupAttributeNames() {
		return Chunk.getKeySet(markupAttributes);
	}

	/**
	 * @see com.lowagie.text.MarkupAttributes#getMarkupAttributes()
	 */
	public Properties getMarkupAttributes() {
		return markupAttributes;
	}

	/**
	 * Tags this image with an ICC profile.
	 * 
	 * @param profile
	 *            the profile
	 */
	public void tagICC(ICC_Profile profile) {
		this.profile = profile;
	}

	/**
	 * Checks is the image has an ICC profile.
	 * 
	 * @return the ICC profile or <CODE>null</CODE>
	 */
	public boolean hasICCProfile() {
		return (this.profile != null);
	}

	/**
	 * Gets the images ICC profile.
	 * 
	 * @return the ICC profile
	 */
	public ICC_Profile getICCProfile() {
		return profile;
	}

	/**
	 * Getter for property deflated.
	 * 
	 * @return Value of property deflated.
	 *  
	 */
	public boolean isDeflated() {
		return this.deflated;
	}

	/**
	 * Setter for property deflated.
	 * 
	 * @param deflated
	 *            New value of property deflated.
	 *  
	 */
	public void setDeflated(boolean deflated) {
		this.deflated = deflated;
	}

	/**
	 * Getter for property indexed.
	 * 
	 * @return Value of property indexed.
	 *  
	 */
	public PdfDictionary getAdditional() {
		return this.additional;
	}

	/**
	 * Sets the /Colorspace key.
	 * 
	 * @param additional
	 *            New value of property indexed.
	 */
	public void setAdditional(PdfDictionary additional) {
		this.additional = additional;
	}

	/**
	 * Getter for property smask.
	 * 
	 * @return Value of property smask.
	 *  
	 */
	public boolean isSmask() {
		return this.smask;
	}

	/**
	 * Setter for property smask.
	 * 
	 * @param smask
	 *            New value of property smask.
	 *  
	 */
	public void setSmask(boolean smask) {
		this.smask = smask;
	}

	/**
	 * Gets the X/Y pixel dimensionless aspect ratio.
	 * 
	 * @return the X/Y pixel dimensionless aspect ratio
	 */
	public float getXYRatio() {
		return this.XYRatio;
	}

	/**
	 * Sets the X/Y pixel dimensionless aspect ratio.
	 * 
	 * @param XYRatio
	 *            the X/Y pixel dimensionless aspect ratio
	 */
	public void setXYRatio(float XYRatio) {
		this.XYRatio = XYRatio;
	}

	/**
	 * Gets the left indentation.
	 * 
	 * @return the left indentation
	 */
	public float indentationLeft() {
		return indentationLeft;
	}

	/**
	 * Gets the right indentation.
	 * 
	 * @return the right indentation
	 */
	public float indentationRight() {
		return indentationRight;
	}

	/**
	 * Sets the left indentation.
	 * 
	 * @param f
	 */
	public void setIndentationLeft(float f) {
		indentationLeft = f;
	}

	/**
	 * Sets the right indentation.
	 * 
	 * @param f
	 */
	public void setIndentationRight(float f) {
		indentationRight = f;
	}

	/**
	 * Getter for property originalType.
	 * 
	 * @return Value of property originalType.
	 *  
	 */
	public int getOriginalType() {
		return this.originalType;
	}

	/**
	 * Setter for property originalType.
	 * 
	 * @param originalType
	 *            New value of property originalType.
	 *  
	 */
	public void setOriginalType(int originalType) {
		this.originalType = originalType;
	}

	/**
	 * Getter for property originalData.
	 * 
	 * @return Value of property originalData.
	 *  
	 */
	public byte[] getOriginalData() {
		return this.originalData;
	}

	/**
	 * Setter for property originalData.
	 * 
	 * @param originalData
	 *            New value of property originalData.
	 *  
	 */
	public void setOriginalData(byte[] originalData) {
		this.originalData = originalData;
	}

	/**
	 * Sets the url of the image
	 * 
	 * @param url
	 *            the url of the image
	 */
	public void setUrl(URL url) {
		this.url = url;
	}

	/**
	 * Sets the spacing before this image.
	 * 
	 * @param spacing
	 *            the new spacing
	 */

	public void setSpacingBefore(float spacing) {
		this.spacingBefore = spacing;
	}

	/**
	 * Sets the spacing after this image.
	 * 
	 * @param spacing
	 *            the new spacing
	 */

	public void setSpacingAfter(float spacing) {
		this.spacingAfter = spacing;
	}

	/**
	 * Gets the spacing before this image.
	 * 
	 * @return the spacing
	 */

	public float spacingBefore() {
		return spacingBefore;
	}

	/**
	 * Gets the spacing before this image.
	 * 
	 * @return the spacing
	 */

	public float spacingAfter() {
		return spacingAfter;
	}

	/**
	 * Getter for property widthPercentage.
	 * 
	 * @return Value of property widthPercentage.
	 */
	public float getWidthPercentage() {
		return this.widthPercentage;
	}

	/**
	 * Setter for property widthPercentage.
	 * 
	 * @param widthPercentage
	 *            New value of property widthPercentage.
	 */
	public void setWidthPercentage(float widthPercentage) {
		this.widthPercentage = widthPercentage;
	}

	/**
	 * Gets the layer this image belongs to.
	 * 
	 * @return the layer this image belongs to or <code>null</code> for no
	 *         layer defined
	 */
	public PdfOCG getLayer() {
		return layer;
	}

	/**
	 * Sets the layer this image belongs to.
	 * 
	 * @param layer
	 *            the layer this image belongs to
	 */
	public void setLayer(PdfOCG layer) {
		this.layer = layer;
	}

    private PdfObject simplifyColorspace(PdfObject obj) {
        if (obj == null || !obj.isArray())
            return obj;
        PdfObject first = (PdfObject)(((PdfArray)obj).getArrayList().get(0));
        if (PdfName.CALGRAY.equals(first))
            return PdfName.DEVICEGRAY;
        else if (PdfName.CALRGB.equals(first))
            return PdfName.DEVICERGB;
        else
            return obj;
    }

    /**
     * Replaces CalRGB and CalGray colorspaces with DeviceRGB and DeviceGray.
     */    
    public void simplifyColorspace() {
        if (additional == null)
            return;
        PdfObject value = additional.get(PdfName.COLORSPACE);
        if (value == null || !value.isArray())
            return;
        PdfObject cs = simplifyColorspace(value);
        if (cs.isName())
            value = cs;
        else {
            PdfObject first = (PdfObject)(((PdfArray)value).getArrayList().get(0));
            if (PdfName.INDEXED.equals(first)) {
                ArrayList array = ((PdfArray)value).getArrayList();
                if (array.size() >= 2 && ((PdfObject)array.get(1)).isArray()) {
                     array.set(1, simplifyColorspace((PdfObject)array.get(1)));
                }
            }
        }
        additional.put(PdfName.COLORSPACE, value);
    }
    
    /**
     * Getter for property initialRotation.
     * @return Value of property initialRotation.
     */
    public float getInitialRotation() {
        return this.initialRotation;
    }
    
    /**
     * Some image formats, like TIFF may present the images rotated that have
     * to be compensated.
     * @param initialRotation New value of property initialRotation.
     */
    public void setInitialRotation(float initialRotation) {
        float old_rot = rotation - this.initialRotation;
        this.initialRotation = initialRotation;
        setRotation(old_rot);
    }
    
}