2016年9月27日 星期二

使用Java製作GIF動畫 - AnimatedGifEncoder

今天要來介紹一個對於用Java生成動態GIF特別好用的類別, AnimatedGifEncoder,
由Kevin Weiner所撰寫,

下面以一個簡單的例子來演示如何使用。

需求如下:

  1. 寫一個servlet,其接到request後可輸出一個GIF動畫。
  2. 在一個htm內用<img>的src接接看測試

實作的檔案結構如下:

各檔內容如下(AnimatedGifEncoder.java就不介紹了):

  1. index.html
    <!DOCTYPE html>
    <html>
        <head>
            <title>Animated Gif Test</title>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <style>
                /* 為img加上背景色,測試透明GIF動畫 */
                img {
                    background-color: black;
                }
            </style>
        </head>
        <body>
            <div>Animated Gif Test</div>
            <!-- 測試GIF動畫 -->
            <img src="AnimatedGif.do" />
        </body>
    </html>
  2. AnimatedGif.java
    /*
     * To change this license header, choose License Headers in Project Properties.
     * To change this template file, choose Tools | Templates
     * and open the template in the editor.
     */
    package servlet;
    
    import java.awt.Color;
    import java.awt.Graphics2D;
    import java.awt.image.BufferedImage;
    import java.io.IOException;
    import java.io.OutputStream;
    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import tools.AnimatedGifEncoder;
    
    @WebServlet(name = "AnimatedGif", urlPatterns = {"/AnimatedGif.do"})
    public class AnimatedGif extends HttpServlet {
    
        /**
         * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
         * methods.
         *
         * @param request servlet request
         * @param response servlet response
         * @throws ServletException if a servlet-specific error occurs
         * @throws IOException if an I/O error occurs
         */
        protected void processRequest(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            OutputStream o = response.getOutputStream();
            response.setContentType("image/gif"); //設定-- header -- ContentType
            
            Color transparentColor = Color.WHITE;
            
            AnimatedGifEncoder encoder = new AnimatedGifEncoder();
            encoder.setTransparent(transparentColor); //設定透明色
            encoder.setDelay(100);  //設定frame之間的間隔 (毫秒)
            encoder.setRepeat(0);  //設定重覆迴圈次數(不設就是不重覆), 0:無限, 1:重覆一次...
            encoder.start(o);      //綁定OutputStream  
            
            //產生畫布
            BufferedImage generatedImage = new BufferedImage(100, 100, BufferedImage.TYPE_INT_ARGB);
            //產生繪圖工具
            Graphics2D graphics2D = generatedImage.createGraphics();
            for (int i = 0; i < 10 ; i++){
                //畫底色
                graphics2D.setColor(transparentColor);
                graphics2D.fillRect(0, 0, generatedImage.getWidth(), generatedImage.getHeight());
                //畫圓圈
                graphics2D.setColor(Color.RED);
                graphics2D.drawOval(i*3, 25, 50, 50);
                //加到GIF動畫frame中
                encoder.addFrame(generatedImage);
            }
            graphics2D.dispose(); //釋放資源
     encoder.finish();  //GIF動畫結束
            //串流輸出
            o.flush();
            o.close();
        }
    
        // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
        /**
         * Handles the HTTP <code>GET</code> method.
         *
         * @param request servlet request
         * @param response servlet response
         * @throws ServletException if a servlet-specific error occurs
         * @throws IOException if an I/O error occurs
         */
        @Override
        protected void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            processRequest(request, response);
        }
    
        /**
         * Handles the HTTP <code>POST</code> method.
         *
         * @param request servlet request
         * @param response servlet response
         * @throws ServletException if a servlet-specific error occurs
         * @throws IOException if an I/O error occurs
         */
        @Override
        protected void doPost(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            processRequest(request, response);
        }
    
        /**
         * Returns a short description of the servlet.
         *
         * @return a String containing servlet description
         */
        @Override
        public String getServletInfo() {
            return "Short description";
        }// </editor-fold>
    
    }
    
    
    
成果展示:

原始碼下載:
AnimatedGifEncoderTest.7z

參考資料:

  1. Java – How To Overlay One Image Over Another Using Graphics2D [Tutorial]
  2. 在Java應用程序中創建圖像的方法和技巧
  3. Is there a way to create one Gif image from multiple images in Java? [closed]
  4. 在Java中使用AnimatedGifEncoder生成GIF動畫
  5. [Android] AnimatedGifEncoder
  6. java将gif动态图片分开展示源代码简单示例

沒有留言 :

張貼留言