標籤:exception 處理 ++ throw 擷取 完成 images main ima
1 package utils; 2 3 import java.awt.Graphics2D; 4 import java.awt.image.BufferedImage; 5 import java.io.File; 6 7 import javax.imageio.ImageIO; 8 import javax.swing.ImageIcon; 9 10 public class TestMainPNG{11 12 public static void main(String[] args) throws Exception{13 BufferedImage image = ImageIO.read(new File("C:/Users/grand/Desktop/lanzhou.jpg"));14 // 高度和寬度15 int height = image.getHeight();16 int width = image.getWidth();17 18 // 生產背景透明和內容透明的圖片19 ImageIcon imageIcon = new ImageIcon(image);20 BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_4BYTE_ABGR);21 Graphics2D g2D = (Graphics2D) bufferedImage.getGraphics(); // 擷取畫筆22 g2D.drawImage(imageIcon.getImage(), 0, 0, null); // 繪製Image的圖片23 24 int alpha = 0; // 圖片透明度25 // 外層遍曆是Y軸的像素26 for (int y = bufferedImage.getMinY(); y < bufferedImage.getHeight(); y++) {27 // 內層遍曆是X軸的像素28 for (int x = bufferedImage.getMinX(); x < bufferedImage.getWidth(); x++) {29 int rgb = bufferedImage.getRGB(x, y);30 // 對使用中色彩判斷是否在指定區間內31 if (colorInRange(rgb)){32 alpha = 0;33 }else{34 // 設定為不透明35 alpha = 255;36 }37 // #AARRGGBB 最前兩位為透明度38 rgb = (alpha << 24) | (rgb & 0x00ffffff);39 bufferedImage.setRGB(x, y, rgb);40 }41 }42 // 繪製設定了RGB的新圖片43 g2D.drawImage(bufferedImage, 0, 0, null);44 45 // 產生圖片為PNG46 ImageIO.write(bufferedImage, "png", new File("C:/Users/grand/Desktop/lanzhou.png"));47 MyLogger.logger.info("完成畫圖");48 }49 50 // 判斷是背景還是內容51 public static boolean colorInRange(int color) {52 int red = (color & 0xff0000) >> 16;// 擷取color(RGB)中R位53 int green = (color & 0x00ff00) >> 8;// 擷取color(RGB)中G位54 int blue = (color & 0x0000ff);// 擷取color(RGB)中B位55 // 通過RGB三分量來判斷使用中色彩是否在指定的顏色區間內56 if (red >= color_range && green >= color_range && blue >= color_range){57 return true;58 };59 return false;60 }61 62 //色差範圍0~25563 public static int color_range = 210;64 65 }
說明:左邊圖片是白色的底,右邊圖片是透明的底。
個人感覺:使用畫筆操作的是畫中的內容,透明化是對畫布的操作而不是內容的操作。
java對圖片進行透明化處理