JAVA生成GIF图片

 前面写了利用java合并图片的文章,一位朋友说应该把gif图片不失真的合并起来,自己想想也是,可是自己技术还没过关,所以没有找到解决方法,于是上网GOOGLE一番,以外发现了一套java生成gif图片的方法,现在贴上来,跟大家共同学习。
  先看一下效果图:
  
 
主方法:
  1. import com.sun.image.codec.jpeg.*;
  2. import com.sun.image.codec.*;
  3. import javax.imageio.*;
  4. import java.awt.*;
  5. import java.io.*;
  6. import java.awt.image.*;
  7. public class DrawImage{
  8.     public static void main(String[] args) throws Exception{
  9.         
  10.         
  11.         try
  12.             BufferedImage src = ImageIO.read(new File("Img221785570.jpg")); // ¶ÁÈëÎļþ 
  13.             BufferedImage src1 = ImageIO.read(new File("W.gif")); // ¶ÁÈëÎļþ 
  14.             //BufferedImage src2 = ImageIO.read(new File("c:/ship3.jpg")); // ¶ÁÈëÎļþ 
  15.             AnimatedGifEncoder e = new AnimatedGifEncoder(); 
  16.             e.setRepeat(0); 
  17.             e.start("laoma.gif"); 
  18.             e.setDelay(300); // 1 frame per sec 
  19.             e.addFrame(src); 
  20.             e.setDelay(100); 
  21.             e.addFrame(src1); 
  22.             e.setDelay(100); 
  23.         //  e.addFrame(src2); 
  24.             e.finish(); 
  25.         }catch(IOException e){ 
  26.         e.printStackTrace(); 
  27.         } 
  28.     }
  29. }

其中有两个关键类:

  1. import java.io.*;
  2. import java.awt.*;
  3. import java.awt.image.*;
  4. /**
  5.  * Class AnimatedGifEncoder - Encodes a GIF file consisting of one or
  6.  * more frames.
  7.  * <pre>
  8.  * Example:
  9.  *    AnimatedGifEncoder e = new AnimatedGifEncoder();
  10.  *    e.start(outputFileName);
  11.  *    e.setDelay(1000);   // 1 frame per sec
  12.  *    e.addFrame(image1);
  13.  *    e.addFrame(image2);
  14.  *    e.finish();
  15.  * </pre>
  16.  * No copyright asserted on the source code of this class.  May be used
  17.  * for any purpose, however, refer to the Unisys LZW patent for restrictions
  18.  * on use of the associated LZWEncoder class.  Please forward any corrections
  19.  * to kweiner@fmsware.com.
  20.  *
  21.  * @author Kevin Weiner, FM Software
  22.  * @version 1.03 November 2003
  23.  *
  24.  */
  25. public class AnimatedGifEncoder {
  26.  protected int width; // image size
  27.  protected int height;
  28.  protected Color transparent = null// transparent color if given
  29.  protected int transIndex; // transparent index in color table
  30.  protected int repeat = -1// no repeat
  31.  protected int delay = 0// frame delay (hundredths)
  32.  protected boolean started = false// ready to output frames
  33.  protected OutputStream out;
  34.  protected BufferedImage image; // current frame
  35.  protected byte[] pixels; // BGR byte array from frame
  36.  protected byte[] indexedPixels; // converted frame indexed to palette
  37.  protected int colorDepth; // number of bit planes
  38.  protected byte[] colorTab; // RGB palette
  39.  protected boolean[] usedEntry = new boolean[256]; // active palette entries
  40.  protected int palSize = 7// color table size (bits-1)
  41.  protected int dispose = -1// disposal code (-1 = use default)
  42.  protected boolean closeStream = false// close stream when finished
  43.  protected boolean firstFrame = true;
  44.  protected boolean sizeSet = false// if false, get size from first frame
  45.  protected int sample = 10// default sample interval for quantizer
  46.  /**
  47.   * Sets the delay time between each frame, or changes it
  48.   * for subsequent frames (applies to last frame added).
  49.   *
  50.   * @param ms int delay time in milliseconds
  51.   */
  52.  public void setDelay(int ms) {
  53.   delay = Math.round(ms / 10.0f);
  54.  }
  55.  /**
  56.   * Sets the GIF frame disposal code for the last added frame
  57.   * and any subsequent frames.  Default is 0 if no transparent
  58.   * color has been set, otherwise 2.
  59.   * @param code int disposal code.
  60.   */
  61.  public void setDispose(int code) {
  62.   if (code >= 0) {
  63.    dispose = code;
  64.   }
  65.  }
  66.  /**
  67.   * Sets the number of times the set of GIF frames
  68.   * should be played.  Default is 1; 0 means play
  69.   * indefinitely.  Must be invoked before the first
  70.   * image is added.
  71.   *
  72.   * @param iter int number of iterations.
  73.   * @return
  74.   */
  75.  public void setRepeat(int iter) {
  76.   if (iter >= 0) {
  77.    repeat = iter;
  78.   }
  79.  }
  80.  /**
  81.   * Sets the transparent color for the last added frame
  82.   * and any subsequent frames.
  83.   * Since all colors are subject to modification
  84.   * in the quantization process, the color in the final
  85.   * palette for each frame closest to the given color
  86.   * becomes the transparent color for that frame.
  87.   * May be set to null to indicate no transparent color.
  88.   *
  89.   * @param c Color to be treated as transparent on display.
  90.   */
  91.  public void setTransparent(Color c) {
  92.   transparent = c;
  93.  }
  94.  /**
  95.   * Adds next GIF frame.  The frame is not written immediately, but is
  96.   * actually deferred until the next frame is received so that timing
  97.   * data can be inserted.  Invoking <code>finish()</code> flushes all
  98.   * frames.  If <code>setSize</code> was not invoked, the size of the
  99.   * first image is used for all subsequent frames.
  100.   *
  101.   * @param im BufferedImage containing frame to write.
  102.   * @return true if successful.
  103.   */
  104.  public boolean addFrame(BufferedImage im) {
  105.   if ((im == null) || !started) {
  106.    return false;
  107.   }
  108.   boolean ok = true;
  109.   try {
  110.    if (!sizeSet) {
  111.     // use first frame's size
  112.     setSize(im.getWidth(), im.getHeight());
  113.    }
  114.    image = im;
  115.    getImagePixels(); // convert to correct format if necessary
  116.    analyzePixels(); // build color table & map pixels
  117.    if (firstFrame) {
  118.     writeLSD(); // logical screen descriptior
  119.     writePalette(); // global color table
  120.     if (repeat >= 0) {
  121.      // use NS app extension to indicate reps
  122.      writeNetscapeExt();
  123.     }
  124.    }
  125.    writeGraphicCtrlExt(); // write graphic control extension
  126.    writeImageDesc(); // image descriptor
  127.    if (!firstFrame) {
  128.     writePalette(); // local color table
  129.    }
  130.    writePixels(); // encode and write pixel data
  131.    firstFrame = false;
  132.   } catch (IOException e) {
  133.    ok = false;
  134.   }
  135.   return ok;
  136.  }
  137.  /**
  138.   * Flushes any pending data and closes output file.
  139.   * If writing to an OutputStream, the stream is not
  140.   * closed.
  141.   */
  142.  public boolean finish() {
  143.   if (!started) return false;
  144.   boolean ok = true;
  145.   started = false;
  146.   try {
  147.    out.write(0x3b); // gif trailer
  148.    out.flush();
  149.    if (closeStream) {
  150.     out.close();
  151.    }
  152.   } catch (IOException e) {
  153.    ok = false;
  154.   }
  155.   // reset for subsequent use
  156.   transIndex = 0;
  157.   out = null;
  158.   image = null;
  159.   pixels = null;
  160.   indexedPixels = null;
  161.   colorTab = null;
  162.   closeStream = false;
  163.   firstFrame = true;
  164.   return ok;
  165.  }
  166.  /**
  167.   * Sets frame rate in frames per second.  Equivalent to
  168.   * <code>setDelay(1000/fps)</code>.
  169.   *
  170.   * @param fps float frame rate (frames per second)
  171.   */
  172.  public void setFrameRate(float fps) {
  173.   if (fps != 0f) {
  174.    delay = Math.round(100f / fps);
  175.   }
  176.  }
  177.  /**
  178.   * Sets quality of color quantization (conversion of images
  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值