1. 程式人生 > >Java 生成微信群頭像 九宮格頭像

Java 生成微信群頭像 九宮格頭像

通過獲取使用者網路路徑地址的 頭像.生成一張網路路徑的九宮格頭像. dir是網路伺服器路徑
import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import javax.imageio.ImageIO;
import javax.net.ssl.HttpsURLConnection;

/**
 * 該類是圖片處理類
 * 
 * @author 
 * 
 */
public final class ImageUtil {
    /** 圖片格式:JPG */
    private static final String PICTRUE_FORMATE_JPG = "jpg";

    private ImageUtil() {
    }
/**
     * 生成組合頭像
     * 
     * @param paths
     *            使用者影象
 * @param dir 
 * @param groupId 
 * @return 
     * @throws IOException
     */
    public static boolean getCombinationOfhead(List<String> paths, String dir, String groupId)
            throws IOException {
        List<BufferedImage> bufferedImages = new ArrayList<BufferedImage>();
        // 壓縮圖片所有的圖片生成尺寸同意的 為 50x50
        for (int i = 0; i < paths.size(); i++) {
        	BufferedImage resize2 = ImageUtil.resize2(paths.get(i), 40, 40, true);
            bufferedImages.add(resize2);
        }

        int width = 112; // 這是畫板的寬高

        int height = 112; // 這是畫板的高度

        // BufferedImage.TYPE_INT_RGB可以自己定義可檢視API

        BufferedImage outImage = new BufferedImage(width, height,
                BufferedImage.TYPE_INT_RGB);

        // 生成畫布
        Graphics g = outImage.getGraphics();
        
        Graphics2D g2d = (Graphics2D) g;
        
        // 設定背景色
        g2d.setBackground(new Color(231,231,231));
        
        // 通過使用當前繪圖表面的背景色進行填充來清除指定的矩形。
        g2d.clearRect(0, 0, width, height);
        
        // 開始拼湊 根據圖片的數量判斷該生成那種樣式的組合頭像目前為4中
        int j = 1;
        for (int i = 1; i <= bufferedImages.size(); i++) {
        	if (bufferedImages.size()==9) {
        		if (i<=3) {
        			g2d.drawImage(bufferedImages.get(i - 1), 30 * i + 3 * i
                            - 31, 0, null);
				}else if(i<=6) {
					g2d.drawImage(bufferedImages.get(i - 1),27 * j + 5 * j
                            - 30, 36, null);  
						j++;
				}else{
					g2d.drawImage(bufferedImages.get(i - 1),27 * j + 5 * j-125, 77, null);
							j++;
				}
			}
        	else if (bufferedImages.size()== 8) {
        		if (i<=3) {
        			g2d.drawImage(bufferedImages.get(i - 1), 30 * i + 3 * i
                            - 31, 0, null);
				}else if(i<=6) {
					g2d.drawImage(bufferedImages.get(i - 1),27 * j + 5 * j
                            - 30, 36, null);  
						j++;
				}else{
					g2d.drawImage(bufferedImages.get(i - 1),21*j+9*j-100, 77, null);
							j++;
				}
				
			}
        	
        	else if (bufferedImages.size()== 7) {
        		if (i<=3) {
        			g2d.drawImage(bufferedImages.get(i - 1), 30 * i + 3 * i
                            - 31, 0, null);
				}else if(i<=6) {
					g2d.drawImage(bufferedImages.get(i - 1),27 * j + 5 * j
                            - 30, 36, null);  
						j++;
				}else{
					 g2d.drawImage(bufferedImages.get(i - 1), 3, 75, null);
				}
				
			}
        	
        	
        	else  	if (bufferedImages.size()== 6) {
        		if (i<=3) {
        			 g2d.drawImage(bufferedImages.get(i - 1), 30 * i + 3 * i
                             - 31, 10, null);
				}else {
					 g2d.drawImage(bufferedImages.get(i - 1), 31 * j + 4 * j
	                            - 33, 60, null);
	                    j++;
                }
			}
        	else if (bufferedImages.size()== 5) {
        		if (i<=3) {
        			 g2d.drawImage(bufferedImages.get(i - 1), 30 * i + 3 * i
                             - 28, 10, null);
				}else {
				 g2d.drawImage(bufferedImages.get(i - 1), 48 * j + 8 * j
	                            - 49, 60, null);
	                    j++;
                }
				
			}
        	else if (bufferedImages.size()== 4) {
                if (i <= 2) {
                    g2d.drawImage(bufferedImages.get(i - 1), 50 * i + 4 * i
                            - 50, 4, null);
                } else {
                    g2d.drawImage(bufferedImages.get(i - 1), 50 * j + 4 * j
                            - 50, 58, null);
                    j++;
                }
            } else if (bufferedImages.size() == 3) {
                if (i <= 1) {

                    g2d.drawImage(bufferedImages.get(i - 1), 31, 4, null);

                } else {

                    g2d.drawImage(bufferedImages.get(i - 1), 50 * j + 4 * j
                            - 50, 58, null);

                    j++;
                }

            } else if (bufferedImages.size() == 2) {

                g2d.drawImage(bufferedImages.get(i - 1), 50 * i + 4 * i - 50,
                        31, null);

            } else if (bufferedImages.size() == 1) {

                g2d.drawImage(bufferedImages.get(i - 1), 31, 31, null);

            }

            // 需要改變顏色的話在這裡繪上顏色。可能會用到AlphaComposite類
        }
//        new File(dir + "groupPicture" + File.separatorChar
//				+ groupId.substring(0, 4) + File.separatorChar + groupId+".jpg")
//        String outPath = dir+groupId+".jpg";
        StringBuffer outPath = new StringBuffer().append(dir)
				.append("groupPicture")
				.append(File.separatorChar)
				.append(groupId.substring(0, 4))
				.append(File.separatorChar)
				.append(groupId).append(".jpg");

        String format = "JPG";
         File file = new File(outPath.toString());
         if(!file.exists()){
        	 file.mkdirs();
         }
        	 
        return ImageIO.write(outImage, format, file);
    }

    /**
     * 圖片縮放
     * 
     * @param filePath
     *            圖片路徑
     * @param height
     *            高度
     * @param width
     *            寬度
     * @param bb
     *            比例不對時是否需要補白
     */
    public static BufferedImage resize2(String filePath, int height, int width,
            boolean bb) {
        try {
            double ratio = 0; // 縮放比例
//            System.out.println("圖片縮放"+filePath);
            BufferedImage bi =null;
            if(filePath.indexOf("http://")==0){
            	bi = ImageIO.read(new URL(filePath));
            }else{
            	bi = ImageIO.read(new File(filePath));
            }
            Image itemp = bi.getScaledInstance(width, height,
                    Image.SCALE_SMOOTH);
            // 計算比例
            if ((bi.getHeight() > height) || (bi.getWidth() > width)) {
                if (bi.getHeight() > bi.getWidth()) {
                    ratio = (new Integer(height)).doubleValue()
                            / bi.getHeight();
                } else {
                    ratio = (new Integer(width)).doubleValue() / bi.getWidth();
                }
                AffineTransformOp op = new AffineTransformOp(
                        AffineTransform.getScaleInstance(ratio, ratio), null);
                itemp = op.filter(bi, null);
            }
            if (bb) {
                // copyimg(filePath, "D:\\img");
                BufferedImage image = new BufferedImage(width, height,
                        BufferedImage.TYPE_INT_RGB);
                Graphics2D g = image.createGraphics();
                g.setColor(Color.white);
                g.fillRect(0, 0, width, height);
                if (width == itemp.getWidth(null))
                    g.drawImage(itemp, 0, (height - itemp.getHeight(null)) / 2,
                            itemp.getWidth(null), itemp.getHeight(null),
                            Color.white, null);
                else
                    g.drawImage(itemp, (width - itemp.getWidth(null)) / 2, 0,
                            itemp.getWidth(null), itemp.getHeight(null),
                            Color.white, null);
                g.dispose();
                itemp = image;
            }
            return (BufferedImage) itemp;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    
    public static StringBuffer httpsRequest(String requestUrl, String dir) throws NoSuchAlgorithmException, NoSuchProviderException,
			KeyManagementException, MalformedURLException, IOException,
			ProtocolException, UnsupportedEncodingException {

		URL url = new URL(requestUrl);
		

		InputStream connection1 = url.openStream();


		try {
			byte[] bb=readInputStream(connection1);
			writeImageToDisk(bb,dir+".jpg");
		} catch (Exception e) {
			
			e.printStackTrace();
		}
		return null;
    }
    public static byte[] readInputStream(InputStream inStream) throws Exception{    
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();    
        byte[] buffer = new byte[1024];    
        int len = 0;    
        while( (len=inStream.read(buffer)) != -1 ){    
            outStream.write(buffer, 0, len);    
        }    
        inStream.close();    
        return outStream.toByteArray();    
    }
    
    public static void writeImageToDisk(byte[] img, String fileName){    
        try {    
            File file = new File(fileName);    
            FileOutputStream fops = new FileOutputStream(file);    
            fops.write(img);    
            fops.flush();    
            fops.close();       
        } catch (Exception e) {    
            e.printStackTrace();    
        }    
    }   
}

===========================================================================================================================

測試

 ArrayList<String>picUrls=new ArrayList<>();
			 //1. 根據使用者ID 獲取使用者頭像(集合)
			 //獲取群主頭像
			 String headerPic= userCrowdMapper.getHeaderPic(header);
			 picUrls=userCrowdMapper.userPicUrl(userIds);
			 picUrls.add(headerPic);
			 //當靜態資源與應用分離時,可以獲取網路資源進行圖片合成
//			 boolean flag=ImageUtil.getCombinationOfhead(picUrls,dir,groupId); 
			 //當靜態資源和應用程式在同一伺服器上時,直接從本地磁碟讀取檔案
			 for (int i = 0; i < picUrls.size(); i++) {
				 String url=picUrls.get(i); //獲取當前頭像
				 picUrls.set(i, dir+url.replace(urlImg, ""));//設定為網路路徑頭像
			}
			 //2 呼叫工具類 生成九宮格 並儲存在已有路徑
			 boolean flag=ImageUtil.getCombinationOfhead(picUrls,dir,groupId); 
			 if(flag){
				 String url=urlImg+new StringBuffer().append("groupPicture/").append(groupId.substring(0, 4))
							.append("/").append(groupId).append(".jpg").toString();
		
				crowd.setCrowdPicture(url);
				}