gpt4 book ai didi

Java BufferedImage setRGB、getRGB错误

转载 作者:行者123 更新时间:2023-12-01 12:21:53 29 4
gpt4 key购买 nike

我正在编辑 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, 207 从图像中返回为 204, 203, 203 - 事实上,我更改的每个像素都来自返回为 204, 203, 203。我究竟做错了什么?这根本没有意义。预先感谢!

最佳答案

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

In BufferedImages with a ColorModel the pixel is set to the nearest colour chosen. That means that you might not get the colour you wanted because the colours you can set are limited to the colours in the ColorModel. You can get around that by creating your own BufferedImage and draw the source image onto that and then manipulate those pixels.

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

关于Java BufferedImage setRGB、getRGB错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26608754/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com