简体   繁体   English

从BufferedImage读取像素-颜色值错误

[英]Reading pixels from BufferedImage - wrong color values

When a spaceship is destroyed I create list containg pixels of spaceship's image. 当一艘宇宙飞船被摧毁时,我创建了一个包含宇宙飞船图像像素的列表。 Pixels are objects of my Pixel class. 像素是我的Pixel类的对象。 After creating list it's added to main list where various actions are performed on them. 创建列表后,将其添加到主列表中,对它们执行各种操作。 This is how my code looks like: 这是我的代码的样子:

//Code which creates an array
List<Pixel> pixels = new LinkedList<>();
BufferedImage buff = (BufferedImage)image;
for (int px = 0; px < buff.getWidth(); px++) {
    for (int py = 0; py < buff.getHeight(); py++) {
        int rgb = buff.getRGB(px, py);
        int red = (rgb & 0x00ff0000) >> 16;
        int green = (rgb & 0x0000ff00) >> 8;
        int blue = rgb & 0x000000ff;
        int alpha = (rgb >> 24) & 0xff;
        if (alpha == 255) {
            pixels.add(new Pixel(px, py, red, green, blue));
        }
    }
}
//Pixel class constructor
Pixel(float x, float y, int red, int green, int blue) {
    super(x, y);
    BufferedImage buff = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);
    WritableRaster raster = buff.getRaster();
    //LOOKS EVERYTHING IS OKAY SINCE THIS LINE SO THE ERROR MUST BE SOMEWHERE IN THOSE 2 LINES
    raster.setPixel(0, 0, new int[]{red, blue, green, 255});
    image = buff;
}

Short explanation: image is private field of type Image. 简短说明:image是类型为Image的私有字段。 It's used in repaint() method which paints pixel using drawImage() method. 它用于repaint()方法,该方法使用drawImage()方法绘制像素。 And about my problem: Eveything works almost okay. 关于我的问题:一切正常。 Pixels are creating on right position but all are violet-color. 像素在正确的位置上创建,但是全部都是紫色。 They have different tones(brighter and darker) but are all violet instead of having the same colors as image's colors! 它们具有不同的色调(更亮和更暗),但是都是紫罗兰色,而不是具有与图像颜色相同的颜色! Why is this happening? 为什么会这样呢? Why violet? 为什么是紫罗兰色? Could someone help me unserstand this strange behaviour? 有人可以帮助我理解这种奇怪的行为吗?

It's probably a mixup of green and blue values in your setPixel method. setPixel方法中可能是绿色和蓝色值的混合。 Colors are usually given in RGB order, which is how you unpacked them from your BufferedImage . 颜色通常以RGB顺序给出,这就是从BufferedImage解压缩颜色的方式。

Instead of 代替

raster.setPixel(0, 0, new int[]{red, blue, green, 255});

try 尝试

raster.setPixel(0, 0, new int[]{red, green, blue, 255});

If that doesn't work you may have to tinker with different variable orders in your array until it looks right. 如果这样不起作用,则可能必须对阵列中的不同可变顺序进行修改,直到看起来正确为止。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM