获取透明背景的坐标list
/**
* 获取透明背景的坐标list
*
* @param file
* @return
*/
@SneakyThrows
public static int[][] getTransparentByUrl(File file) {
BufferedImage bufImg = null;
try {
bufImg = ImageIO.read(file);
} catch (IOException e) {
throw new BusinessException("file地址错误" + e);
}
int height = bufImg.getHeight();
int width = bufImg.getWidth();
int[][] place = new int[width][height];
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
int pixel = bufImg.getRGB(i, j);
if (pixel >> 24 == 0) {
place[i][j] = 0;
} else {
place[i][j] = 1;
}
}
}
return place;
}
将特定颜色替换为透明
/**
* 将特定颜色替换为透明
* @param filePath 待处理图片地址(G:\java\BeiShi\1234\bigRBG.png
* @param targetFile 保存目标地址(G:\java\BeiShi\1234\bigRBG.png
* @param rbgColor 替换颜色(255,255,255)
* @throws IOException
*/
public static void changeImgColor(String filePath,String targetFile, int[] rbgColor) throws IOException {
String substring = filePath.substring(filePath.lastIndexOf("."));
Image image = ImageIO.read(new File(filePath));
//将原图片的二进制转化为ImageIcon
ImageIcon imageIcon = new ImageIcon(image);
int width = imageIcon.getIconWidth();
int height = imageIcon.getIconHeight();
//图片缓冲流
BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_4BYTE_ABGR);
Graphics2D graphics2D = (Graphics2D) bufferedImage.getGraphics();
graphics2D.drawImage(imageIcon.getImage(), 0, 0, imageIcon.getImageObserver());
//将特定颜色替换为透明
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
int rgb = bufferedImage.getRGB(i, j);
int[] write = new int[3];
write[0] = (rgb & 0xff0000) >> 16;
write[1] = (rgb & 0xff00) >> 8;
write[2] = (rgb & 0xff);
if (write==rbgColor) {
rgb = (0) | (rgb & 0x00ffffff);
bufferedImage.setRGB(i, j, rgb);
}
}
}
ImageIO.write(bufferedImage, substring, new File(targetFile));
}
查询图片是否为透明图
/**
* 查询图片是否为透明图
*
* @param file 文件路径G:\java\BeiShi\excel_imgs\***.png
* @return boolean
*/
public static boolean isTransparentByFile(File file) {
BufferedImage bufImg = null;
try {
bufImg = ImageIO.read(file);
} catch (IOException e) {
throw new BusinessException("file地址错误" + e);
}
int height = bufImg.getHeight();
int width = bufImg.getWidth();
boolean isTransparent = false;
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
int pixel = bufImg.getRGB(i, j);
if (pixel >> 24 == 0) {
isTransparent = true;
break;
}
}
}
return isTransparent;
}
借鉴文章:https://blog.csdn.net/qq_41940067/article/details/118609354