Java BufferedImage setRGB,getRGB错误

时间:2014-10-28 12:46:45

标签: java bufferedimage

我正在编辑BufferedImage。

更改图片中的像素后,我会检查以确保新值符合我的预期。但是,它们没有更改为指定的像素颜色

我认为它可能与Alpha值有关,所以我最近添加了一个从原始像素中提取Alpha值的步骤,并确保在创建要插回图像的新颜色时使用该值

System.out.println(newColors[0] + ", " + newColors[1] + ", " + newColors[2]);
Color oldColor = new Color(image.getRGB(x, y));
Color newColor = new Color(newColors[0], newColors[1], newColors[2], oldColor.getAlpha()); // create a new color from the RGB values.
image.setRGB(x, y, newColor.getRGB());// set the RGB of the pixel in the image.

for (int col : getRGBs(x,y)) {
    System.out.println(col);
}

方法getRGBs()返回一个数组

  • 索引0是红色值
  • 索引1为绿色
  • 索引2为蓝色。

输出如下:

206, 207, 207
204
203
203

正如您所看到的,值206, 207, 207204, 203, 203的形式从图像中返回 - 事实上,我更改的每个像素都会以204, 203, 203的形式返回。 我究竟做错了什么?它没有意义。 提前谢谢!

2 个答案:

答案 0 :(得分:1)

我在网上找到了自己的答案,我将在下面总结一下:

  

在带有ColorModel的BufferedImages中,像素设置为所选的最接近的颜色。这意味着您可能无法获得所需的颜色,因为您可以设置的颜色仅限于ColorModel中的颜色。   您可以通过创建自己的BufferedImage并将源图像绘制到其上然后操纵这些像素来解决这个问题。

BufferedImage original = ImageIO.read(new File(file.getPath()));

    image= new BufferedImage(original.getWidth(), original.getHeight(), BufferedImage.TYPE_3BYTE_BGR);
    image.getGraphics().drawImage(original, 0, 0, null);
     for(int y = 0; y < original.getHeight(); y++){
            for(int x = 0; x < original.getWidth(); x++){
                image.setRGB(x,y, original.getRGB(x,y));
            }
     }

解决了这个问题。很明显,ColorModel没有我指定的颜色,因此将像素调整到最接近的颜色。

Source

答案 1 :(得分:0)

我猜你要找的是WritableRaster,它有助于写入读取的图像。 使用ImageIO将最终更改写入新文件或提供相同的文件进行更改。

   public class ImageTest {

    BufferedImage image;
    File imageFile = new File("C:\\Test\\test.bmp");

    public ImageTest() {
        try {
            image = ImageIO.read(imageFile);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public void editImage() throws IOException {
        WritableRaster wr = image.getRaster();
        int width = image.getWidth();
        int height = image.getHeight();

        for(int ii=0; ii<width; ii++) {
            for(int jj=0; jj<height; jj++) {
                int color = image.getRGB(ii, jj);
                wr.setSample(ii, jj, 0 , 156);
            }
        }

        ImageIO.write(image, "BMP", new File("C:\\Test\\test.bmp"));
    }

    public static void main(String[] args) throws IOException {
        ImageTest test = new ImageTest();
        test.editImage();
    }

}
相关问题