Source for gnu.javax.imageio.png.PNGFile

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