因需要將一張白色背景圖片處理為透明色,因此上網上搜了搜處理方案,可以通過ps,和美圖秀秀,但是我電腦上並沒有這兩個軟件,下載安裝太耗時。從網上搜了搜發現原來可以使用java代碼進行處理,代碼如下:
import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; import javax.swing.ImageIcon; public class Application { public static void main(String[] args) throws IOException { BufferedImage image = ImageIO.read(new File("D:\\鄭州-買房\\subway-graph.jpg")); // 高度和寬度 int height = image.getHeight(); int width = image.getWidth(); // 生產背景透明和內容透明的圖片 ImageIcon imageIcon = new ImageIcon(image); BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_4BYTE_ABGR); Graphics2D g2D = (Graphics2D) bufferedImage.getGraphics(); // 獲取畫筆 g2D.drawImage(imageIcon.getImage(), 0, 0, null); // 繪制Image的圖片 int alpha = 0; // 圖片透明度 // 外層遍歷是Y軸的像素 for (int y = bufferedImage.getMinY(); y < bufferedImage.getHeight(); y++) { // 內層遍歷是X軸的像素 for (int x = bufferedImage.getMinX(); x < bufferedImage.getWidth(); x++) { int rgb = bufferedImage.getRGB(x, y); // 對當前顏色判斷是否在指定區間內 if (colorInRange(rgb)) { alpha = 0; } else { // 設置為不透明 alpha = 255; } // #AARRGGBB 最前兩位為透明度 rgb = (alpha << 24) | (rgb & 0x00ffffff); bufferedImage.setRGB(x, y, rgb); } } // 繪制設置了RGB的新圖片 g2D.drawImage(bufferedImage, 0, 0, null); // 生成圖片為PNG ImageIO.write(bufferedImage, "png", new File("D:\\鄭州-買房\\subway-graph2.jpg")); System.out.println("完成畫圖"); } // 判斷是背景還是內容 public static boolean colorInRange(int color) { int red = (color & 0xff0000) >> 16;// 獲取color(RGB)中R位 int green = (color & 0x00ff00) >> 8;// 獲取color(RGB)中G位 int blue = (color & 0x0000ff);// 獲取color(RGB)中B位 // 通過RGB三分量來判斷當前顏色是否在指定的顏色區間內 if (red >= color_range && green >= color_range && blue >= color_range) { return true; } ; return false; } // 色差范圍0~255 public static int color_range = 210; }
代碼來自:http://www.cnblogs.com/TheoryDance/p/7094376.html
處理前后效果對比:
處理前 | 處理后 |
![]() |
![]() |