【问题标题】:How to set custom RGB values while looping through image in Java如何在 Java 中循环遍历图像时设置自定义 RGB 值
【发布时间】:2018-11-20 02:19:42
【问题描述】:

我正在循环浏览具有 X 和 Y 坐标的图像。但是,我只能使用以下方法设置 sRGB 值:image.setRGB(int x, int y, int rgb);

我想为当前的 X 和 Y 坐标设置一个自定义的 RED、GREEN 和 BLUE 值。在这种情况下,新的 RGB 值是原始 RGB 值的平均值。

我得到的结果是蓝色图像而不是灰度图像。

for (int y = 0; y < imageInput.getHeight(); y++) {
        for (int x = 0; x < imageInput.getWidth(); x++) {
            int clr = imageInput.getRGB(x, y);
            Color color = new Color(clr);
            int red = color.getRed();
            int green = color.getGreen();
            int blue = color.getBlue();

            int sumRGB = red + green + blue;
            int avg = sumRGB/3;
            System.out.println("sRGB: " + clr);
            System.out.println("Input Image: x= " + x + " y= " + y + " [" + red + "," + green + "," + blue + "]");
            System.out.println("Avg RGB: " + avg);

            imageCopy.setRGB(x, y, avg);
            int clrCopy = imageCopy.getRGB(x, y);
            color = new Color(clrCopy);

            red = color.getRed();
            green = color.getGreen();
            blue = color.getBlue();
            System.out.println("Output Image: x= " + x + " y= " + y + " [" + red + "," + green + "," + blue + "]\n");
        }
    }

【问题讨论】:

标签: java image colors rgb


【解决方案1】:

你可以写

Color greyScaleColor = new Color(avg, avg, avg);
int rgbValueForGrey = greyScaleColor.getRGB();

这将为您提供您需要在imageCopy 中设置的int 值。

【讨论】:

  • 最好0x010101 * avg 以节省为每个像素创建对象
  • @MarkJeronimus 如果您有不同的做法,欢迎您编写自己的答案。
  • 如果它有助于解决问题,请accept the answer。还请重新访问您的earlier questions,其中似乎都没有接受答案!
猜你喜欢
  • 2011-12-06
  • 1970-01-01
  • 2020-01-26
  • 2012-06-03
  • 1970-01-01
  • 2020-12-10
  • 1970-01-01
  • 1970-01-01
  • 2013-07-16
相关资源
最近更新 更多