java图片透明_Java实现对图片透明化处理
因需要將一張白色背景圖片處理為透明色,因此上網(wǎng)上搜了搜處理方案,可以通過ps和其他圖片軟件,但是我電腦上并沒有這兩個軟件,下載安裝太耗時。從網(wǎng)上搜了搜發(fā)現(xiàn)原來可以使用 Java 代碼進(jìn)行處理,代碼如下:
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 linuxidc {
public static void main(String[] args) throws IOException {
BufferedImage image = ImageIO.read(new File("/home/linuxidc/linuxidc.com/linuxidc.com.jpg"));
// 高度和寬度
int height = image.getHeight();
int width = image.getWidth();
// 生產(chǎn)背景透明和內(nèi)容透明的圖片
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++) {
// 內(nèi)層遍歷是X軸的像素
for (int x = bufferedImage.getMinX(); x < bufferedImage.getWidth(); x++) {
int rgb = bufferedImage.getRGB(x, y);
// 對當(dāng)前顏色判斷是否在指定區(qū)間內(nèi)
if (colorInRange(rgb)) {
alpha = 0;
} else {
// 設(shè)置為不透明
alpha = 255;
}
// #AARRGGBB 最前兩位為透明度
rgb = (alpha << 24) | (rgb & 0x00ffffff);
bufferedImage.setRGB(x, y, rgb);
}
}
// 繪制設(shè)置了RGB的新圖片
g2D.drawImage(bufferedImage, 0, 0, null);
// 生成圖片為PNG
ImageIO.write(bufferedImage, "png", new File("/home/linuxidc/linuxidc.com/linuxidc.com.png"));
System.out.println("完成畫圖");
}
// 判斷是背景還是內(nèi)容
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三分量來判斷當(dāng)前顏色是否在指定的顏色區(qū)間內(nèi)
if (red >= color_range && green >= color_range && blue >= color_range) {
return true;
}
;
return false;
}
// 色差范圍0~255
public static int color_range = 210;
}
處理前后效果對比:
總結(jié)
以上是生活随笔為你收集整理的java图片透明_Java实现对图片透明化处理的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 电子海图数据购买、安装、更新及使用注意事
- 下一篇: Linux⼊侵排查