java - java Swing 中可以修改图像的颜色吗?

标签 java swing colors

我正在制作模拟动画,我的实体使用的图像是黑白的小 PNG 文件(如果这有什么区别的话)。我想知道在作为 BufferedImage 导入后是否有任何方法可以更改图像的颜色(例如,将黑色更改为红色,或在黑色上覆盖红色滤镜)?或者我最好的选择是在 Java 之外创建图标的单独颜色版本并将它们作为单独的图像导入?

最佳答案

您可以使用 java.awt.image.RGBImageFilter 类

我个人还没有玩过这个,我采用了另一种方式,即将图标放入像素(整数)数组中并自行操作。

有了这个,你可以创建一个 ImageSourceInt 的实例(我这样调用它),传递一个 ImageIcon,摆弄它

(canvasData 是 ARGB-int 格式的像素数组 - 每个 channel 1 个字节 = 4 个字节 = 1 个 int)

并检索 BufferedImage( View ,而不是副本)以供 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;
}

}

关于java - java Swing 中可以修改图像的颜色吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21041108/

相关文章:

java - 如何在Java(TelNet)中实现接收套接字的事件?

java - java中的按位逻辑运算符

java - 如何在 Java 文本编辑器中为关键字着色?

javascript - 在白色上将 RGB 转换为 RGBA

html 颜色与图像颜色

java - 开发支持多语言的java客户端时优化jar文件大小(图片)

java - 如何在多个窗口中更新JList?

java - 使用netbeans、使用PreparedStatement和ResultSet从MYSql检索数据

javascript - 使用按钮javascript更改某些东西的颜色

java - 服务器断开连接后如何在 Spring MVC 中保持客户端 session 处于 Activity 状态