PNGFile.java 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. /* PNGFile.java -- High-level representation of a PNG file.
  2. Copyright (C) 2006 Free Software Foundation
  3. This file is part of GNU Classpath.
  4. GNU Classpath is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 2, or (at your option)
  7. any later version.
  8. GNU Classpath is distributed in the hope that it will be useful, but
  9. WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  11. General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with GNU Classpath; see the file COPYING. If not, write to the
  14. Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
  15. 02110-1301 USA.
  16. Linking this library statically or dynamically with other modules is
  17. making a combined work based on this library. Thus, the terms and
  18. conditions of the GNU General Public License cover the whole
  19. combination.
  20. As a special exception, the copyright holders of this library give you
  21. permission to link this library with independent modules to produce an
  22. executable, regardless of the license terms of these independent
  23. modules, and to copy and distribute the resulting executable under
  24. terms of your choice, provided that you also meet, for each linked
  25. independent module, the terms and conditions of the license of that
  26. module. An independent module is a module which is not derived from
  27. or based on this library. If you modify this library, you may extend
  28. this exception to your version of the library, but you are not
  29. obligated to do so. If you do not wish to do so, delete this
  30. exception statement from your version. */
  31. package gnu.javax.imageio.png;
  32. import java.io.InputStream;
  33. import java.io.OutputStream;
  34. import java.io.IOException;
  35. import java.util.Vector;
  36. import java.awt.image.BufferedImage;
  37. import java.awt.image.WritableRaster;
  38. import java.awt.image.ColorModel;
  39. import java.awt.color.ColorSpace;
  40. public class PNGFile
  41. {
  42. /**
  43. * The PNG file signature.
  44. */
  45. private static final byte[] signature = new byte[]
  46. { (byte)137, 80, 78, 71, 13, 10, 26, 10 };
  47. /**
  48. * The end chunk in raw form, no need for anything fancy here, it's just
  49. * 0 bytes of length, the "IEND" tag and its CRC.
  50. */
  51. private static final byte[] endChunk = new byte[]
  52. { 0, 0, 0, 0, (byte)0x49, (byte)0x45, (byte)0x4E, (byte)0x44,
  53. (byte)0xAE, (byte)0x42, (byte)0x60, (byte)0x82 };
  54. /**
  55. * The loaded data.
  56. */
  57. private Vector chunks;
  58. /**
  59. * The Header chunk
  60. */
  61. private PNGHeader header;
  62. /**
  63. * Whether this file has a palette chunk or not.
  64. */
  65. private boolean hasPalette;
  66. /**
  67. * Image width and height.
  68. */
  69. private int width, height;
  70. /**
  71. * The decoder, if any.
  72. */
  73. private PNGDecoder decoder;
  74. /**
  75. * The encoder, if any. (Either this or the above must exist).
  76. */
  77. private PNGEncoder encoder;
  78. /**
  79. * The source of this PNG (if encoding)
  80. */
  81. private BufferedImage sourceImage;
  82. /**
  83. * Creates a PNGFile object from an InputStream.
  84. */
  85. public PNGFile(InputStream in) throws IOException, PNGException
  86. {
  87. PNGChunk chunk;
  88. byte[] fileHdr = new byte[8];
  89. chunks = new Vector();
  90. hasPalette = false;
  91. if( in.read( fileHdr ) != 8 )
  92. throw new IOException("Could not read file header.");
  93. if( !validateHeader( fileHdr ) )
  94. throw new PNGException("Invalid file header. Not a PNG file.");
  95. chunk = PNGChunk.readChunk( in, false );
  96. if( !(chunk instanceof PNGHeader) )
  97. throw new PNGException("First chunk not a header chunk.");
  98. header = (PNGHeader)chunk;
  99. if( !header.isValidChunk() )
  100. throw new PNGException("First chunk not a valid header.");
  101. System.out.println(header);
  102. decoder = new PNGDecoder( header );
  103. // Read chunks.
  104. do
  105. {
  106. chunk = PNGChunk.readChunk( in, false );
  107. /*
  108. * We could exit here or output some kind of warning.
  109. * But in the meantime, we'll just silently drop invalid chunks.
  110. */
  111. if( chunk.isValidChunk() )
  112. {
  113. if( chunk instanceof PNGData )
  114. decoder.addData( (PNGData)chunk );
  115. else // Silently ignore multiple headers, and use only the first.
  116. if( chunk.getType() != PNGChunk.TYPE_END )
  117. {
  118. chunks.add( chunk );
  119. hasPalette |= ( chunk instanceof PNGPalette );
  120. }
  121. }
  122. else
  123. System.out.println("WARNING: Invalid chunk!");
  124. }
  125. while( chunk.getType() != PNGChunk.TYPE_END );
  126. if( header.isIndexed() && !hasPalette )
  127. throw new PNGException("File is indexed color and has no palette.");
  128. width = header.getWidth();
  129. height = header.getHeight();
  130. }
  131. /**
  132. * Creates a PNG file from an existing BufferedImage.
  133. */
  134. public PNGFile(BufferedImage bi) throws PNGException
  135. {
  136. sourceImage = bi;
  137. width = bi.getWidth();
  138. height = bi.getHeight();
  139. chunks = new Vector();
  140. encoder = new PNGEncoder( bi );
  141. header = encoder.getHeader();
  142. if( header.isIndexed() )
  143. chunks.add( encoder.getPalette() );
  144. // Do the compression and put the data chunks in the list.
  145. chunks.addAll( encoder.encodeImage() );
  146. }
  147. /**
  148. * Writes a PNG file to an OutputStream
  149. */
  150. public void writePNG(OutputStream out) throws IOException
  151. {
  152. out.write( signature ); // write the signature.
  153. header.writeChunk( out );
  154. for( int i = 0; i < chunks.size(); i++ )
  155. {
  156. PNGChunk chunk = ((PNGChunk)chunks.elementAt(i));
  157. chunk.writeChunk( out );
  158. }
  159. out.write( endChunk );
  160. }
  161. /**
  162. * Check 8 bytes to see if it's a valid PNG header.
  163. */
  164. private boolean validateHeader( byte[] hdr )
  165. {
  166. if( hdr.length != 8 )
  167. return false;
  168. for( int i = 0; i < 8; i++ )
  169. if( signature[i] != hdr[i] )
  170. return false;
  171. return true;
  172. }
  173. /**
  174. * Return a loaded image as a bufferedimage.
  175. */
  176. public BufferedImage getBufferedImage()
  177. {
  178. if( decoder == null )
  179. return sourceImage;
  180. WritableRaster r = decoder.getRaster( header );
  181. ColorModel cm;
  182. if( header.isIndexed() )
  183. {
  184. PNGPalette pngp = getPalette();
  185. cm = pngp.getPalette( getColorSpace() );
  186. }
  187. else
  188. cm = decoder.getColorModel( getColorSpace(),
  189. header.getColorType(),
  190. header.getDepth() );
  191. return new BufferedImage(cm, r, false, null);
  192. }
  193. /**
  194. * Find the palette chunk and return it
  195. */
  196. private PNGPalette getPalette()
  197. {
  198. for(int i = 0; i < chunks.size(); i++ )
  199. if( chunks.elementAt(i) instanceof PNGPalette )
  200. return ((PNGPalette)chunks.elementAt(i));
  201. return null;
  202. }
  203. /**
  204. * Return the Color space to use, first preference is ICC profile, then
  205. * a gamma chunk, or returns null for the default sRGB.
  206. */
  207. private ColorSpace getColorSpace()
  208. {
  209. PNGICCProfile icc = null;
  210. PNGGamma gamma = null;
  211. for(int i = 0; i < chunks.size(); i++ )
  212. {
  213. if( chunks.elementAt(i) instanceof PNGICCProfile )
  214. icc = ((PNGICCProfile)chunks.elementAt(i));
  215. else if(chunks.elementAt(i) instanceof PNGGamma )
  216. gamma = ((PNGGamma)chunks.elementAt(i));
  217. }
  218. if( icc != null )
  219. return icc.getColorSpace();
  220. // if( gamma != null && !header.isGrayscale())
  221. // return gamma.getColorSpace( header.isGrayscale() );
  222. return null;
  223. }
  224. }