GIFFile.java 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710
  1. /* GIFFile.java -- GIF decoder
  2. Copyright (C) 2006 Free Software Foundation, Inc.
  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.gif;
  32. import java.io.IOException;
  33. import java.io.InputStream;
  34. import java.util.Vector;
  35. /**
  36. * GIFFile - reads a GIF file.
  37. *
  38. * This class only does the bare minimum work, and returns the data in raw
  39. * formats (described below). The class is J2ME compatible, and hopefully
  40. * we can keep it that way without any significant overhead.
  41. *
  42. * @author Sven de Marothy.
  43. */
  44. public class GIFFile
  45. {
  46. // "NETSCAPE2.0" - identifier
  47. private final static byte[] nsBlock = new byte[]
  48. {0x4e, 0x45, 0x54, 0x53, 0x43, 0x41, 0x50, 0x45, 0x32, 0x2e, 0x30 };
  49. /**
  50. * Block identifiers
  51. */
  52. private final static int EXTENSION = 0x21;
  53. private final static int LOCAL = 0x2C;
  54. private final static int TERMINATOR = 0x3B;
  55. /**
  56. * Extension block types
  57. */
  58. private final static int EXTENSION_COMMENT = 254;
  59. private final static int EXTENSION_GCONTROL = 249;
  60. private final static int EXTENSION_APPLICATION = 255;
  61. /**
  62. * Undraw commands for animation.
  63. */
  64. private final static int UNDRAW_OVERWRITE = 1;
  65. private final static int UNDRAW_RESTORE_BACKGROUND = 2;
  66. private final static int UNDRAW_RESTORE_PREVIOUS = 3;
  67. /**
  68. * Image position and dimensions (images may be partial)
  69. */
  70. private int x, y, width, height;
  71. /**
  72. * Global dimensions
  73. */
  74. private int globalWidth, globalHeight;
  75. /**
  76. * Background color index.
  77. */
  78. private byte bgIndex;
  79. /**
  80. * Number of colors
  81. */
  82. private int nColors;
  83. /**
  84. * Global palette, if any
  85. */
  86. private byte[] globalPalette;
  87. /**
  88. * Any
  89. */
  90. private boolean hasGlobalColorMap;
  91. /**
  92. * Local palette, if any (used if available)
  93. */
  94. private byte[] localPalette;
  95. /**
  96. * Interlaced GIF or not?
  97. */
  98. private boolean interlaced;
  99. /**
  100. * Has transparency?
  101. */
  102. private boolean hasTransparency;
  103. /**
  104. * Undraw mode (animations)
  105. */
  106. private int undraw;
  107. /**
  108. * Transparent index;
  109. */
  110. private int transparentIndex;
  111. /**
  112. * The uncompressed raster
  113. */
  114. private byte[] raster;
  115. /**
  116. * The compressed data (freed after uncompressing)
  117. */
  118. private byte[] compressedData;
  119. /**
  120. * Frame delay in 100ths of a second ( centiseconds, metrically )
  121. */
  122. private int duration;
  123. /**
  124. * Indices used during decompression
  125. */
  126. private int dataBlockIndex;
  127. /**
  128. * The file comment , if a comment block exists.
  129. */
  130. private String comment;
  131. /**
  132. * Fields used by getBits()
  133. */
  134. private int remainingBits = 0;
  135. private int currentBits = 0;
  136. /**
  137. * Netscape animation extension
  138. */
  139. private boolean isLooped = false;
  140. /** Number of loops, 0 = infinite */
  141. private int loops;
  142. /**
  143. * Additional frames if it's an animated GIF.
  144. */
  145. private Vector animationFrames;
  146. /**
  147. * Loads the file from an input stream, which is not closed.
  148. * @throws IOException if an I/O error occured.
  149. * @throws GIFException if some file parsing error occured
  150. */
  151. public GIFFile(InputStream in) throws IOException, GIFException
  152. {
  153. // Validate the signature
  154. if( !readSignature( in ) )
  155. throw new GIFException("Invalid GIF signature.");
  156. {
  157. byte[] data = new byte[7];
  158. if (in.read(data) != 7)
  159. throw new IOException("Couldn't read global descriptor.");
  160. globalWidth = ((data[1] & 0xFF) << 8) | (data[0] & 0xFF);
  161. globalHeight = ((data[3] & 0xFF) << 8) | (data[2] & 0xFF);
  162. byte flags = data[4];
  163. bgIndex = data[5];
  164. nColors = (1 << (( flags & 0x07) + 1));
  165. hasGlobalColorMap = ((flags & 0x80) != 0);
  166. }
  167. if( hasGlobalColorMap )
  168. {
  169. globalPalette = new byte[ nColors * 3 ];
  170. if( in.read( globalPalette ) != nColors * 3 )
  171. throw new IOException("Couldn't read color map.");
  172. }
  173. int c = in.read();
  174. while( c == EXTENSION )
  175. {
  176. readExtension( in );
  177. c = in.read();
  178. }
  179. if( c != LOCAL )
  180. throw new GIFException("Extension blocks not followed by a local descriptor ("+c+")");
  181. loadImage( in );
  182. c = in.read();
  183. if( c == TERMINATOR ) // Not an animated GIF.
  184. return;
  185. // Load animation frames. Just quit if an error occurs instead
  186. // of throwing an exception.
  187. animationFrames = new Vector();
  188. try
  189. {
  190. while( c != TERMINATOR )
  191. {
  192. animationFrames.add( new GIFFile( this, in, c ) );
  193. c = in.read();
  194. }
  195. }
  196. catch(IOException ioe)
  197. {
  198. }
  199. catch(GIFException gife)
  200. {
  201. }
  202. }
  203. /**
  204. * Constructor for additional animation frames.
  205. */
  206. private GIFFile(GIFFile parent, InputStream in, int c)
  207. throws IOException, GIFException
  208. {
  209. // Copy global properties.
  210. globalWidth = parent.globalWidth;
  211. globalHeight = parent.globalHeight;
  212. nColors = parent.nColors;
  213. globalPalette = parent.globalPalette;
  214. hasGlobalColorMap = parent.hasGlobalColorMap;
  215. interlaced = parent.interlaced;
  216. comment = parent.comment;
  217. isLooped = parent.isLooped;
  218. loops = parent.loops;
  219. while( c == EXTENSION )
  220. {
  221. readExtension( in );
  222. c = in.read();
  223. }
  224. if( c != LOCAL )
  225. throw new GIFException("Extension blocks not followed by a local descriptor ("+c+")");
  226. loadImage( in );
  227. }
  228. /**
  229. * Reads a GIF file signature from an inputstream and checks it.
  230. *
  231. * @param in - the stream (reads 6 bytes, does not close or reset).
  232. * @return true if the signature is a valid GIF signature.
  233. * @throws IOException if the signature could not be read.
  234. */
  235. public static boolean readSignature( InputStream in ) throws IOException
  236. {
  237. byte[] data = new byte[6];
  238. if (in.read(data) != 6)
  239. throw new IOException("Couldn't read signature.");
  240. if( data[0] != 0x47 || data[1] != 0x49 || data[2] != 0x46 ||
  241. data[3] != 0x38 ) // GIF8
  242. return false;
  243. if( (data[4] != 0x39 && data[4] != 0x37) || // 7 | 9
  244. (data[5] != 0x61 && data[5] != 0x62) ) // 'a' or 'b'
  245. return false;
  246. return true;
  247. }
  248. /**
  249. * Loads the image local descriptor and then loads/decodes the image raster,
  250. * and then performs any necessary postprocessing like deinterlacing.
  251. */
  252. private void loadImage(InputStream in)
  253. throws IOException, GIFException
  254. {
  255. readLocal( in );
  256. try
  257. {
  258. decodeRaster( in );
  259. }
  260. catch(ArrayIndexOutOfBoundsException aioobe)
  261. {
  262. throw new GIFException("Error decompressing image.");
  263. }
  264. if( interlaced ) // Clean up
  265. deinterlace();
  266. packPixels();
  267. }
  268. /**
  269. * Pack the pixels if it's a 2, 4 or 16 color image.
  270. * While GIF may support any number of colors from 2-256, we won't bother
  271. * trying to pack pixels not resulting in even byte boundaries.
  272. * (AWT doesn't support that anyway, and most apps do the same.)
  273. */
  274. private void packPixels()
  275. {
  276. if( nColors != 2 && nColors != 4 && nColors != 16 )
  277. return;
  278. int nbits = 1;
  279. int ppbyte = 8;
  280. if( nColors == 4 )
  281. {
  282. nbits = 2;
  283. ppbyte = 4;
  284. }
  285. else if( nColors == 16 )
  286. {
  287. nbits = 4;
  288. ppbyte = 2;
  289. }
  290. int rem = (width & (ppbyte - 1));
  291. int w = ( rem == 0 ) ? (width / ppbyte) :
  292. ((width + ppbyte - rem) / ppbyte);
  293. byte[] nr = new byte[ w * height ];
  294. for(int j = 0; j < height; j++)
  295. {
  296. for(int i = 0; i < width - ppbyte; i += ppbyte)
  297. for(int k = 0; k < ppbyte; k++)
  298. nr[ j * w + (i / ppbyte) ] |= (byte)((raster[ width * j + i + k ]
  299. << (8 - nbits * (1 + k))));
  300. for(int i = 0; i < rem; i++)
  301. nr[ j * w + w - 1 ] |= (byte)((raster[ width * j + width - rem + i ]
  302. << (nbits * (rem - i))));
  303. }
  304. raster = nr;
  305. }
  306. /**
  307. * Returns the (global) width
  308. */
  309. public int getWidth()
  310. {
  311. return width;
  312. }
  313. /**
  314. * Returns the image height
  315. */
  316. public int getHeight()
  317. {
  318. return height;
  319. }
  320. /**
  321. * Returns the # of colors.
  322. */
  323. public int getNColors()
  324. {
  325. return nColors;
  326. }
  327. /**
  328. * Returns whether the GIF has transparency.
  329. */
  330. public boolean hasTransparency()
  331. {
  332. return hasTransparency;
  333. }
  334. /**
  335. * Returns the index of the transparent color.
  336. */
  337. public int getTransparentIndex()
  338. {
  339. return transparentIndex;
  340. }
  341. /**
  342. * Retuns the GIF file comment, or null if none exists.
  343. */
  344. public String getComment()
  345. {
  346. return comment;
  347. }
  348. /**
  349. * Get duration of the frame for animations.
  350. */
  351. public int getDuration()
  352. {
  353. return duration;
  354. }
  355. /**
  356. * Deinterlaces the image.
  357. */
  358. private void deinterlace()
  359. {
  360. byte[] nr = new byte[ width * height ];
  361. int n = 0;
  362. for(int i = 0; i < ((height + 7) >> 3); i++)
  363. {
  364. System.arraycopy( raster, n, nr, width * i * 8, width );
  365. n += width;
  366. }
  367. for(int i = 0; i < ((height + 3) >> 3); i++)
  368. {
  369. System.arraycopy( raster, n, nr, width * ( 8 * i + 4 ), width );
  370. n += width;
  371. }
  372. for(int i = 0; i < (height >> 2); i++)
  373. {
  374. System.arraycopy( raster, n, nr, width * (4 * i + 2), width );
  375. n += width;
  376. }
  377. for(int i = 0; i < (height >> 1); i++)
  378. {
  379. System.arraycopy( raster, n, nr, width * (2 * i + 1), width );
  380. n += width;
  381. }
  382. raster = nr;
  383. }
  384. /**
  385. * Reads the local descriptor
  386. */
  387. private void readLocal(InputStream in) throws IOException
  388. {
  389. byte[] data = new byte[9];
  390. if (in.read(data) != 9)
  391. throw new IOException("Couldn't read local descriptor.");
  392. x = ((data[1] & 0xFF) << 8) | (data[0] & 0xFF);
  393. y = ((data[3] & 0xFF) << 8) | (data[2] & 0xFF);
  394. width = ((data[5] & 0xFF) << 8) | (data[4] & 0xFF);
  395. height = ((data[7] & 0xFF) << 8) | (data[6] & 0xFF);
  396. byte flags = data[8];
  397. interlaced = (( flags & 0x40 ) != 0);
  398. if( (flags & 0x80) != 0 )
  399. { // has a local color map
  400. int nLocalColors = (1 << (( flags & 0x07) + 1));
  401. if( !hasGlobalColorMap )
  402. nColors = nLocalColors;
  403. localPalette = new byte[ nLocalColors * 3 ];
  404. if( in.read( localPalette ) != nLocalColors * 3 )
  405. throw new IOException("Couldn't read color map.");
  406. }
  407. }
  408. /**
  409. * Returns the image's palette in raw format
  410. * (r0,g0,b0,r1,g1,b2..r(Ncolors-1),g(Ncolors-1),b(Ncolors-1))
  411. */
  412. public byte[] getRawPalette()
  413. {
  414. return hasGlobalColorMap ? globalPalette : localPalette;
  415. }
  416. /**
  417. * Returns the image file for animated gifs.
  418. */
  419. public GIFFile getImage( int index )
  420. {
  421. if( index == 0 )
  422. return this;
  423. if( animationFrames == null )
  424. throw new ArrayIndexOutOfBoundsException("Only one image in file");
  425. return (GIFFile)animationFrames.elementAt( index - 1 );
  426. }
  427. /**
  428. * Return the image's raw image data.
  429. * If the color depth is 1,2 or 4 bits per pixel the pixels are packed
  430. * and the scanlines padded up to the nearest byte if needed.
  431. */
  432. public byte[] getRawImage()
  433. {
  434. return raster;
  435. }
  436. /**
  437. * Return the number of images in the GIF file
  438. */
  439. public int nImages()
  440. {
  441. if( animationFrames != null )
  442. return 1 + animationFrames.size();
  443. return 1;
  444. }
  445. /**
  446. * Handles extension blocks.
  447. */
  448. private void readExtension(InputStream in) throws IOException, GIFException
  449. {
  450. int functionCode = in.read();
  451. byte[] data = readData(in);
  452. switch( functionCode )
  453. {
  454. case EXTENSION_COMMENT: // comment block
  455. comment = new String(data, "8859_1");
  456. break;
  457. case EXTENSION_GCONTROL: // Graphics control extension
  458. undraw = (data[0] & 0x1C) >> 2;
  459. // allegedly there can be bad values of this.
  460. if( undraw < 1 && undraw > 3 ) undraw = 1;
  461. hasTransparency = ((data[0] & 0x01) == 1);
  462. transparentIndex = (data[3] & 0xFF);
  463. duration = ((data[2] & 0xFF) << 8) | (data[1] & 0xFF);
  464. break;
  465. // Application extension. We only parse the Netscape animation
  466. // extension here. Which is the only one most use anyway.
  467. case EXTENSION_APPLICATION:
  468. boolean isNS = true;
  469. for(int i = 0; i < nsBlock.length; i++ )
  470. if( nsBlock[i] != data[i] )
  471. isNS = false;
  472. if( isNS )
  473. {
  474. isLooped = true;
  475. loops = ((data[12] & 0xFF) << 8) | (data[13] & 0xFF);
  476. }
  477. break;
  478. default:
  479. break;
  480. }
  481. }
  482. /**
  483. * Reads a series of data blocks and merges them into a single one.
  484. */
  485. private byte[] readData(InputStream in) throws IOException
  486. {
  487. Vector v = new Vector();
  488. int totalBytes = 0;
  489. int n = in.read();
  490. do
  491. {
  492. totalBytes += n;
  493. byte[] block = new byte[ n ];
  494. in.read(block);
  495. v.add(block);
  496. n = in.read();
  497. }
  498. while( n > 0 );
  499. n = 0;
  500. byte[] bigBuffer = new byte[ totalBytes ];
  501. for( int i = 0; i < v.size(); i++ )
  502. {
  503. byte[] block = (byte[])v.elementAt(i);
  504. System.arraycopy(block, 0, bigBuffer, n, block.length);
  505. n += block.length;
  506. }
  507. return bigBuffer;
  508. }
  509. /**
  510. * Loads a compressed image block and decompresses it.
  511. */
  512. private void decodeRaster(InputStream in) throws IOException
  513. {
  514. int initialCodeSize = in.read();
  515. compressedData = readData( in );
  516. dataBlockIndex = 0;
  517. int rasterIndex = 0; // Index into the raster
  518. int clearCode = (1 << initialCodeSize); // 256 usually
  519. int endCode = clearCode + 1; // The stop code.
  520. raster = new byte[ width * height ];
  521. int codeSize = initialCodeSize + 1;
  522. int code = getBits( codeSize ); // = clear
  523. int nextCode = endCode + 1;
  524. /*
  525. * Initialize LZW dictionary
  526. *
  527. * First index - code #
  528. * Second index:
  529. * 0 = color index
  530. * 1 = parent (-1 - no parent)
  531. * 2 = first value
  532. * 3 - depth
  533. * The latter two aren't strictly necessary but make things faster, since
  534. * copying the values forward is faster than going back and looking.
  535. */
  536. short[][] dictionary = new short[ 4096 ][ 4 ];
  537. for(short i = 0; i < nColors; i ++ )
  538. {
  539. dictionary[i][0] = i; // color index
  540. dictionary[i][1] = -1; // parent
  541. dictionary[i][2] = i; // first
  542. dictionary[i][3] = 1; // depth
  543. }
  544. code = getBits( codeSize ); // get second code
  545. raster[ rasterIndex++ ] = (byte)dictionary[code][0];
  546. int old = code;
  547. code = getBits( codeSize ); // start at the third code
  548. int c;
  549. do
  550. {
  551. if( code == clearCode )
  552. {
  553. codeSize = initialCodeSize + 1;
  554. nextCode = endCode + 1;
  555. // get and output second code
  556. code = getBits( codeSize );
  557. raster[ rasterIndex++ ] = (byte)dictionary[code][0];
  558. old = code;
  559. }
  560. else
  561. {
  562. dictionary[nextCode][1] = (short)old; // parent = old
  563. dictionary[nextCode][2] = dictionary[old][2]; // first pixel
  564. dictionary[nextCode][3] = (short)(dictionary[old][3] + 1); // depth
  565. // appended pixel = first pixel of c
  566. if( code < nextCode )
  567. {
  568. dictionary[nextCode][0] = dictionary[code][2];
  569. old = code;
  570. }
  571. else // first of old
  572. {
  573. dictionary[nextCode][0] = dictionary[old][2];
  574. old = nextCode;
  575. }
  576. c = old;
  577. // output the code c
  578. int depth = dictionary[c][3];
  579. for( int i = depth - 1; i >= 0; i-- )
  580. {
  581. raster[ rasterIndex + i ] = (byte)dictionary[c][0];
  582. c = dictionary[c][1]; // go to parent.
  583. }
  584. rasterIndex += depth;
  585. nextCode ++;
  586. if( codeSize < 12 && nextCode >= (1 << codeSize) )
  587. codeSize++;
  588. }
  589. code = getBits( codeSize );
  590. }
  591. while( code != endCode && dataBlockIndex < compressedData.length );
  592. compressedData = null; // throw away compressed data.
  593. }
  594. /**
  595. * Returns nbits number of bits (in the LSBs) from compressedData
  596. */
  597. private int getBits( int nbits )
  598. {
  599. while( nbits > remainingBits )
  600. {
  601. int c = (compressedData[ dataBlockIndex++ ] & 0xFF) << remainingBits;
  602. currentBits |= c;
  603. remainingBits += 8;
  604. }
  605. int rval = (currentBits & ((1 << nbits) - 1));
  606. currentBits = (currentBits >> nbits);
  607. remainingBits -= nbits;
  608. return rval;
  609. }
  610. /**
  611. * Generic exception used by GIFFile to report decoding errors.
  612. */
  613. public static class GIFException extends Exception
  614. {
  615. public GIFException(String message)
  616. {
  617. super(message);
  618. }
  619. }
  620. }