java圖片處理——多張圖片合成一張Gif圖片並播放或Gif拆分紅多張圖片

一、多張jpg圖合成gif動畫linux

   /**  
     * 把多張jpg圖片合成一張  
     * @param pic String[] 多個jpg文件名 包含路徑  
     * @param newPic String 生成的gif文件名 包含路徑  
     */  
    private synchronized void jpgToGif(String pic[], String newPic) {  
        try {  
            AnimatedGifEncoder e = new AnimatedGifEncoder();          
      e.setRepeat(0); e.start(newPic); BufferedImage src[] = new BufferedImage[pic.length]; for (int i = 0; i < src.length; i++) { e.setDelay(200); //設置播放的延遲時間 src[i] = ImageIO.read(new File(pic[i])); // 讀入須要播放的jpg文件 e.addFrame(src[i]); //添加到幀中 } e.finish(); } catch (Exception e) { System.out.println( "jpgToGif Failed:"); e.printStackTrace(); } }

二、gif動畫分解成多張jpg測試

  /**  
    * 把gif圖片按幀拆分紅jpg圖片           
    * @param gifName String 小gif圖片(路徑+名稱)  
    * @param path String 生成小jpg圖片的路徑  
    * @return String[] 返回生成小jpg圖片的名稱  
    */  
   private synchronized String[] splitGif(String gifName,String path) {  
       try {  
           GifDecoder decoder = new GifDecoder();  
           decoder.read(gifName);  
           int n = decoder.getFrameCount(); //獲得frame的個數  
           String[] subPic = new String[n];  
           String tag = this.getTag();  
           for (int i = 0; i < n; i++) {  
               BufferedImage frame = decoder.getFrame(i); //獲得幀  
               //int delay = decoder.getDelay(i); //獲得延遲時間  
               //生成小的JPG文件  
               subPic[i] = path + String.value(i)+ ".jpg";  
               FileOutputStream out = new FileOutputStream(subPic[i]);  
               ImageIO.write(frame, "jpeg", out);  
               JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);     
              encoder.encode(frame); //存盤   
              out.flush();   
              out.close();  
           }  
           return subPic;  
       } catch (Exception e) {  
           System.out.println( "splitGif Failed!");  
           e.printStackTrace();  
           return null;  
       }  
}

三、根據提供的文字生成jpg圖片字體

   /**
     * 根據提供的文字生成jpg圖片
     * @param s String  文字
     * @param smallWidth int  每一個字的寬度和高度是同樣的
     * @param bgcolor Color  背景色
     * @param fontcolor Color  字色
     * @param fontPath String 字體文件
     * @param jpgname String jpg圖片名
     * @return
     */
    private String createJpgByFont(String s, int smallWidth,Color bgcolor,Color fontcolor,String fontPath,String jpgname) {
        try {
            BufferedImage bimage = new BufferedImage(s.length()*smallWidth,
                                                         smallWidth,BufferedImage.TYPE_INT_RGB);
            Graphics2D g = bimage.createGraphics();
            g.setColor(bgcolor); //背景色
            g.fillRect(0, 0, smallWidth, smallWidth); //畫一個矩形
            g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON); //去除鋸齒(當設置的字體過大的時候,會出現鋸齒)
            g.setColor(fontcolor); //字的顏色
            File file = new File(fontPath);  //字體文件
            Font font = Font.createFont(Font.TRUETYPE_FONT, file); //根據字體文件所在位置,建立新的字體對象(此語句在jdk1.5下面才支持)  
            g.setFont(font.deriveFont((float) smallWidth));   //font.deriveFont(float f)複製當前 Font 對象並應用新設置字體的大小
            g.drawString(s,0, smallWidth); //在指定座標除添加文字
            g.dispose();
            FileOutputStream out = new FileOutputStream(jpgname); //指定輸出文件
            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
            JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bimage);
            param.setQuality(50f, true);
            encoder.encode(bimage, param); //存盤
            out.flush();
            out.close();
        } catch (Exception e) {
            System.out.println( "createJpgByFont Failed!");
            e.printStackTrace();
        }
    }

四、多張小jpg圖合成一張大JPG圖,在這裏對大圖只做寬度限制,不作高度限制動畫

    /**
     * 將多個小圖片合成一張大jpg圖  (小的jpg圖片按照行列順序平鋪)
     * @param smallJPG ArrayList 一組小的jpg圖片
     * @param bigWidth int 大圖寬度
     * @param smallWidth int  單個文字生成的小圖的寬度和高度是一致的
     * @return 
     */
    private void createBigJPG(ArrayList smallJPG, int bigWidth,
                                int smallHeigh,Color bgColor ,String picName) {
        try {
            if (bigWidth < smallWidth) //若是大圖片的高度比小圖片的高度還小 直接返回
                return;
            int colCount = bigWidth / smallWidth; //每行放置的字數
            int leftMargin = (int) ((bigWidth - colCount * smallWidth) / 2f); //左邊距
            int rowCount = smallJPG.size();  //小圖行數 
            int setWidth = bigWidth; //每列中間不留空隙,只留左右邊距
            int setHeight = smallWidth * rowCount ; 
            //按照大圖片寬高繪製一個背景圖片
            BufferedImage bufImage = new BufferedImage(setWidth, setHeight,
                    BufferedImage.TYPE_INT_RGB);
            Graphics2D g = bufImage.createGraphics();
            g.setColor(bgColor); //背景的顏色
            g.fillRect(0, 0, setWidth, setHeight);
            int y = 0; //縱座標
            for (int i = 0; i < rowCount; i++) { //遍歷每行
                ArrayList col = (ArrayList) (smallJPG.get(i));
                int x = leftMargin; //橫座標  可能會出現左邊距
                for (int j = 0; j < col.size(); j++) {
                    String jpgname = (String) (col.get(j));
                    ImageIcon icon = new ImageIcon(jpgname);
                    Image img = icon.getImage();
                    int imgWidth = img.getHeight(null);
                    g.drawImage(img, x, y, null);
                    x += imgWidth;
                }
                y += (smallWidth);  
            }
            g.dispose();
            FileOutputStream out = new FileOutputStream(picName);  //指定輸出文件
            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);  //設置文件格式
            JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bufImage); //從圖片緩衝中讀取
            param.setQuality(50f, true);
            encoder.encode(bufImage, param); //存盤
            out.flush();
            out.close();
        } catch (Exception e) {
            System.out.println( "createBigJPG Failed!");
            e.printStackTrace();    
        }
    }

五、根據指定字符串生成圖片this

//根據str,font的樣式以及輸出文件目錄
public static void createImage(String str,Font font,File outFile) throws Exception{
  //獲取font的樣式應用在str上的整個矩形
  Rectangle2D r=font.getStringBounds(str, new FontRenderContext(AffineTransform.getScaleInstance(1, 1),false,false));
  int unitHeight=(int)Math.floor(r.getHeight());//獲取單個字符的高度
  //獲取整個str用了font樣式的寬度這裏用四捨五入後+1保證寬度絕對能容納這個字符串做爲圖片的寬度
  int width=(int)Math.round(r.getWidth())+1;
  int height=unitHeight+3;//把單個字符的高度+3保證高度絕對能容納字符串做爲圖片的高度
  //建立圖片
  BufferedImage image=new BufferedImage(width,height,BufferedImage.TYPE_INT_BGR);
  Graphics g=image.getGraphics();
  g.setColor(Color.WHITE);
  g.fillRect(0, 0, width, height);//先用白色填充整張圖片,也就是背景
  g.setColor(Color.black);//在換成黑色
  g.setFont(font);//設置畫筆字體
  g.drawString(str, 0, font.getSize());//畫出字符串
  g.dispose();
  ImageIO.write(image, "png", outFile);//輸出png圖片
}

六、多個圖片疊加url

public static void combineImage(List<String> urlList, int width,
            int height, String destPath, String imgFormat) throws IOException {
        BufferedImage combinedImage = new BufferedImage(width, height,
                BufferedImage.TYPE_INT_ARGB);
        Graphics g = combinedImage.getGraphics();
        for (String urlStr : urlList) {
            URL url = new URL(urlStr);
            URLConnection conn = url.openConnection();
            conn.setReadTimeout(10 * 1000);
            InputStream in = conn.getInputStream();
            BufferedImage image = ImageIO.read(in);
            g.drawImage(image, 0, 0, width, height, null);
        }
        ImageIO.write(combinedImage, imgFormat, new File(destPath));
}

注:spa

(1)AnimatedGifEncoder和GifDecoder,以及這兩個類涉及到的相關類,在網上搜索一下就能夠找到。.net

(2)在linux系統下,若是你想支持更多系統外的字體,使用下面兩句話,能夠不用爲系統添加字體,直接把字體文件拷貝到相應位置便可,可是須要jdk1.5環境。code

File file = new File(fontPath);  //字體文件
Font font = Font.createFont(Font.TRUETYPE_FONT, file); //根據字體文件所在位置,建立新的字體對象
若是是jdk1.5如下版本則須要爲系統添加字體,由於createFont(int fontFormat, File fontFile) 
這個方法,是從1.5纔開始有的。orm

(3)g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);

我在測試中發現,當設置的字體過大的時候,會出現很明星的鋸齒,後來在網上找到了這個解決方法。

(4)有了以上幾個方法,就能夠作出更好看的閃信了。我也是由於需求才寫下這些方法的,美工作了一些熱門詞彙的gif圖片,在短信轉彩信遇到這些詞彙時,要使用提供的圖片替換文字。

本文轉自:http://blog.csdn.net/ycb1689/article/details/8071714

相關文章
相關標籤/搜索