我正在制作模拟动画,我正在为我的实体使用的图像是黑白两色的小PNG文件(如果这有什么不同)。我想知道一旦它被导入为BufferedImage,是否有任何方法可以改变图像的颜色(例如,将黑色更改为红色,或将红色滤镜覆盖在黑色上)?或者我最好选择在Java之外创建单独的彩色版本的图标并将它们作为单独的图像导入?
答案 0 :(得分:2)
我个人没有玩过它,我采用了另一种方式,即将图标放入像素数组(int)并自行操作。
有了它,你可以创建一个ImageSourceInt实例(我称之为)传递ImageIcon,摆弄它
(canvasData是ARGB-int格式的像素数组 - 每个通道1byte = 4个字节= 1个int)
并检索BufferedImage(视图,而不是副本),以便与Swing一起使用。
对于后者,请调用getReferenceImage()方法。
顺便说一句,如果您不了解scanSize(成像中的常用术语),只需将其视为图像的宽度。
(对不起代码格式错误,我是新来的)
public class ImageSourceInt implements ImageSource {
int[] canvasData;
int width;
int height;
int scanSize;
int lineCount;
/**
* @param source make sure it is loaded or this ImageSource will be empty.<br>
* sizeIncrementWidth and sizeIncrementHeight are set to 1
*/
public ImageSourceInt(ImageIcon source){
if (source == null) {
this.canvasData = new int[0];
return;
}
this.width = source.getIconWidth();
this.height = source.getIconHeight();
this.scanSize = source.getIconWidth();
this.lineCount = source.getIconHeight();
this.canvasData = new int[this.width*this.height];
// PixelGrabber(Image img, int x, int y, int w, int h, int[] pix, int
// off, int scansize)
PixelGrabber grabber = new PixelGrabber(source.getImage(), 0,
0, this.width, this.height, this.canvasData, 0, this.scanSize);
try {
grabber.grabPixels();
} catch (InterruptedException e) {
e.printStackTrace();// must not be...
}
}
/**
* @return a BufferedImage with the data of this ImageSource (referenced)<br>
* IMPORTANT: if the size changed, the BufferedImage will get invalid, causing strange effects or exceptions
*/
public BufferedImage getReferenceImage(){
DataBuffer buf = new DataBufferInt(this.canvasData, this.canvasData.length);
WritableRaster wRaster = Raster.createPackedRaster(buf, this.getWidth(), this.getHeight(), this.getScanSize(),
new int[]{0x00FF0000, 0x0000FF00, 0x000000FF, 0xFF000000}, new Point());
BufferedImage bi = new BufferedImage(ColorModel.getRGBdefault(), wRaster, false, null);
return bi;
}
}