我正在尝试将Robot.createScreenCapture函数生成的RGB图像转换为ARGB图像。我的目标是在两个图像之间的像素没有变化时设置透明度但我得到黑色。如下图所示。
例如BufferedImage,如下所示:
BufferedImage currImage = robot.createScreenCapture(new Rectangle(x, y, width,height));
以下功能旨在创建ARGB像素。
private BufferedImage bufferedImagesEqual(BufferedImage prevImage,
BufferedImage currImage) {
boolean changed = false;
BufferedImage imagePart = new BufferedImage(currImage.getWidth(), currImage.getHeight(), BufferedImage.TYPE_INT_ARGB);
if (prevImage.getWidth() == currImage.getWidth()
&& prevImage.getHeight() == currImage.getHeight()) {
for (int x = 0; x < currImage.getWidth(); x++) {
for (int y = 0; y < prevImage.getHeight(); y++) {
int argb = currImage.getRGB(x, y);
if (prevImage.getRGB(x, y) != currImage.getRGB(x, y)){
// return false;
// currImage.setRGB(x, y, 0);
if(!changed){
changed = true;
}
}
else {
imagePart.setRGB(x, y, 0xff000000);
}
}
}
} else {
return imagePart;
}
if(changed){
return imagePart;
}else {
return null;
}
}
答案 0 :(得分:1)
从前后图像开始...
使用new Color(0, 0, 0, 0)
代替0xff000000
(当像素相等时绘制SOMETHING),我得到了
使用...
import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
public class ConvertBuffer {
public static void main(String[] args) {
try {
BufferedImage before = ImageIO.read(new File("/Before.jpg"));
BufferedImage after = ImageIO.read(new File("/After.jpg"));
BufferedImage result = bufferedImagesEqual(before, after);
JLabel label = new JLabel(new ImageIcon(result));
label.setOpaque(true);
label.setBackground(Color.BLUE);
JOptionPane.showMessageDialog(null, label);
} catch (Exception e) {
e.printStackTrace();
}
}
private static BufferedImage bufferedImagesEqual(BufferedImage prevImage,
BufferedImage currImage) {
boolean changed = false;
BufferedImage imagePart = new BufferedImage(currImage.getWidth(), currImage.getHeight(), BufferedImage.TYPE_INT_ARGB);
if (prevImage.getWidth() == currImage.getWidth()
&& prevImage.getHeight() == currImage.getHeight()) {
for (int x = 0; x < currImage.getWidth(); x++) {
for (int y = 0; y < prevImage.getHeight(); y++) {
if (prevImage.getRGB(x, y) != currImage.getRGB(x, y)) {
// return false;
// currImage.setRGB(x, y, 0);
if (!changed) {
changed = true;
}
imagePart.setRGB(x, y, currImage.getRGB(x, y));
} else {
imagePart.setRGB(x, y, new Color(0, 0, 0, 0).getRGB());
}
}
}
} else {
return imagePart;
}
if (changed) {
return imagePart;
} else {
return null;
}
}
}
所以,除非你有一个可以使用的示例图像,否则这是我们能做的最好的...