Java 實現圖片拼接


今天小編接到一個小小的任務:將xml中base64編碼格式的圖片拼接成一個圖片,再以base64編碼格式放回到xml中

直接貼上代碼:(只附上圖片拼接的代碼)

【用於將多個圖片拼接成一張圖片】

 1 /**
 2  * 合並任數量的圖片成一張圖片
 3  * 
 4  * @param isHorizontal
 5  *            true代表水平合並,fasle代表垂直合並
 6  * @param imgs
 7  *            待合並的圖片數組
 8  * @return
 9  * @throws IOException
10  */
11 private BufferedImage mergeImage(boolean isHorizontal, BufferedImage... imgs) throws IOException {
12     // 生成新圖片
13     BufferedImage destImage = null;
14     // 計算新圖片的長和高
15     int allw = 0, allh = 0, allwMax = 0, allhMax = 0;
16     // 獲取總長、總寬、最長、最寬
17     for (int i = 0; i < imgs.length; i++) {
18         BufferedImage img = imgs[i];
19         allw += img.getWidth();
20         allh += img.getHeight();
21         if (img.getWidth() > allwMax) {
22             allwMax = img.getWidth();
23         }
24         if (img.getHeight() > allhMax) {
25             allhMax = img.getHeight();
26         }
27     }
28     // 創建新圖片
29     if (isHorizontal) {
30         destImage = new BufferedImage(allw, allhMax, BufferedImage.TYPE_INT_RGB);
31     } else {
32         destImage = new BufferedImage(allwMax, allh, BufferedImage.TYPE_INT_RGB);
33     }
34     // 合並所有子圖片到新圖片
35     int wx = 0, wy = 0;
36     for (int i = 0; i < imgs.length; i++) {
37         BufferedImage img = imgs[i];
38         int w1 = img.getWidth();
39         int h1 = img.getHeight();
40         // 從圖片中讀取RGB
41         int[] ImageArrayOne = new int[w1 * h1];
42         ImageArrayOne = img.getRGB(0, 0, w1, h1, ImageArrayOne, 0, w1); // 逐行掃描圖像中各個像素的RGB到數組中
43         if (isHorizontal) { // 水平方向合並
44             destImage.setRGB(wx, 0, w1, h1, ImageArrayOne, 0, w1); // 設置上半部分或左半部分的RGB
45         } else { // 垂直方向合並
46             destImage.setRGB(0, wy, w1, h1, ImageArrayOne, 0, w1); // 設置上半部分或左半部分的RGB
47         }
48         wx += w1;
49         wy += h1;
50     }
51     return destImage;
52 }

以上代碼僅供參考,如有問題,還請大神們多多指教


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM