1. 程式人生 > >關於 java 顯示GIF

關於 java 顯示GIF

1.java 直接使用JLabel顯示GIF圖片速度總會特別快不能控制,需要自己寫控制元件去實現JLaebl的功能


package Main;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import javax.swing.JLabel;

import com.sun.imageio.plugins.gif.GIFImageMetadata;

public class GifComponent extends JLabel {  
        private static final long serialVersionUID = 1L;  
        private GifBean[] gifBeans;  
        private Map<Integer, Integer[]> gifBeanMap = new HashMap<Integer, Integer[]>();  
        private int index = 0;  
        private int delayFactor;  
        private Timer timer;  
      
        /**
         *  
         * @param gifFile
         * @param delayFactor
         *            顯示gif每幀圖片的時間因子
         */  
        public GifComponent(File gifFile, int delayFactor,int width,int height) {  
        setDelayFactor(delayFactor);  
        setGifFile(gifFile,width,height);  
        }  
      
        /**
         * 設定Gif檔案
         *  
         * @param gifFile
         */  
        public void setGifFile(File gifFile,int width,int height) {  
        ImageReader reader = null;  
        try {  
            ImageInputStream imageIn = ImageIO.createImageInputStream(gifFile);  
            Iterator<ImageReader> iter = ImageIO  
                .getImageReadersByFormatName("gif");  
            if (iter.hasNext()) {  
            reader = iter.next();  
            }  
            reader.setInput(imageIn, false);  
            gifBeanMap.clear();  
            gifBeans = new GifBean[reader.getNumImages(true)];  
            GIFImageMetadata meta = null;  
            for (int i = 0; i < gifBeans.length; i++) {  
            meta = (GIFImageMetadata) reader.getImageMetadata(i);  
            gifBeans[i] = new GifBean();  
            
            BufferedImage originalImage =reader.read(i);
            BufferedImage newImage = new BufferedImage(width,height,originalImage.getType());
            Graphics g = newImage.getGraphics();
            g.drawImage(originalImage, 0,0,width,height,null);
            g.dispose();
            
            gifBeans[i].image = newImage;  
            gifBeans[i].x = meta.imageLeftPosition;  
            gifBeans[i].y = meta.imageTopPosition;  
            gifBeans[i].width = meta.imageWidth;  
            gifBeans[i].height = meta.imageHeight;  
            gifBeans[i].disposalMethod = meta.disposalMethod;  
            gifBeans[i].delayTime = meta.delayTime == 0 ? 1  
                : meta.delayTime;  
            }  
            for (int i = 1; i < gifBeans.length; i++) {  
            if (gifBeans[i].disposalMethod == 2) {  
                gifBeanMap.put(new Integer(i), new Integer[] { i });  
                continue;  
            }  
            int firstIndex = getFirstIndex(i);  
            List<Integer> list = new ArrayList<Integer>();  
            for (int j = firstIndex; j <= i; j++) {  
                list.add(j);  
            }  
            gifBeanMap.put(new Integer(i), list.toArray(new Integer[] {}));  
            }  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
        setTimer();  
        }  
      
        private synchronized void setTimer() {  
        if (timer != null) {  
            timer.cancel();  
        }  
        timer = new Timer("show gif");  
        timer.schedule(new TimerTask() {  
            @Override  
            public void run() {  
            repaint();  
            try {  
                Thread.sleep(gifBeans[index].delayTime * delayFactor);  
            } catch (InterruptedException e) {  
            }  
            index++;  
            if (index >= gifBeans.length) {  
                index = 0;  
            }  
            }  
      
        }, 0, 1);  
      
        }  
      
        /**
         * 設定時間因子
         *  
         * @param delayFactor
         */  
        public void setDelayFactor(int delayFactor) {  
        this.delayFactor = delayFactor;  
        }  
      
        @Override  
        protected void paintComponent(Graphics g) {  
        g.drawImage(gifBeans[0].image, gifBeans[0].x, gifBeans[0].y, this);  
        if (index > 0) {  
            Integer[] array = gifBeanMap.get(index);  
            for (Integer i : array) {  
            g.drawImage(gifBeans[i].image, gifBeans[i].x, gifBeans[i].y,  
                this);  
            }  
        }  
        }  
      
        private int getFirstIndex(int index) {  
        int tempIndex = index;  
        while (tempIndex > 1) {  
            if (tempIndex - 1 > 0  
                && gifBeans[tempIndex - 1].disposalMethod == 2) {  
            return index;  
            }  
            tempIndex--;  
        }  
        return tempIndex;  
        }  
      
        /**
         * 用於保持gif每幀圖片的資訊
         */  
        public class GifBean {  
        public BufferedImage image;  
        public int x;  
        public int y;  
        public int width;  
        public int height;  
        public int disposalMethod;  
        public int delayTime;  
        }  
      
    } 


在Jframe 中加入該元件的方法:

public GIFShow(String pathOfGif) {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(500, 200, 421, 322);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);
        
        // 使用系統自帶的Label顯示GIF
//        label = new JLabel("");
//        label.setBounds(0, 0, 413, 288);
//        contentPane.add(label);        
//        ImageIcon ic1=new ImageIcon(pathOfGif);
//        ic1.setImage(ic1.getImage().getScaledInstance(label.getWidth(), label.getHeight(), Image.SCALE_DEFAULT));
//        label.setIcon(ic1);
        
        
        
        //使用自己的元件顯示GIF
        GifComponent gifComponent=new GifComponent(new File(pathOfGif), 120,413,288);
        gifComponent.setBounds(0, 0, 413, 288);
        contentPane.add(gifComponent);
    }


其中改變Bufferdimage 的尺寸大小的方法:

BufferedImage originalImage = 你的原圖片

int width = 寬度;
int height = 高度;
BufferedImage newImage = new BufferedImage(width,height,originalImage.getType());
Graphics g = newImage.getGraphics();
g.drawImage(originalImage, 0,0,width,height,null);
g.dispose();
newImage  中儲存的便是改變尺寸之後的Bufferdimage