在java中改变图像颜色

时间:2016-08-02 21:42:21

标签: java image

我正在尝试改变图像的颜色。因此我使用了以下代码

public class Picture {

String img_name;
BufferedImage buf_img;
int width;
int height;

public Picture(String name) {
    this.img_name = name;

    try {
        buf_img = ImageIO.read(new File(img_name));
    } catch (IOException ex) {
        Logger.getLogger(Picture.class.getName()).log(Level.SEVERE, null, ex);
    }
}

public Picture(int w, int h) {
    this.width = w;
    this.height = h;
    buf_img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
}

public int width() {
    width = buf_img.getWidth();
    return width;
}

public int height() {
    height = buf_img.getHeight();
    return height;
}

public Color get(int col, int row) {
    Color color = new Color(buf_img.getRGB(col, row));
    return color;
}

public void set(int col, int row, Color color) {
    buf_img.setRGB(col, row, color.getRGB());
}

public void show() {
    try {

        File saveAs = new File("D:\\temp\\" + new Random().nextInt() + ".png");
        ImageIO.write(buf_img, "png", saveAs);

        Desktop.getDesktop().open(saveAs);
    } catch (IOException ex) {
        Logger.getLogger(Picture.class.getName()).log(Level.SEVERE, null, ex);
    }
   }

 }

public class ColorSeparation {

public static void main(String[] args) {

    // read in the picture specified by command-line argument
    Picture picture = new Picture("D:\\qwe1.jpg");
    int width = picture.width();
    int height = picture.height();

    // create three empy pictures of the same dimension
    Picture pictureR = new Picture(width, height);


    // separate colors
    for (int col = 0; col < width; col++) {
        for (int row = 0; row < height; row++) {
            Color color = picture.get(col, row);
            int r = color.getRed();
            int g = color.getGreen();
            int b = color.getBlue();
            pictureR.set(col, row, new Color(r, 0, 0));

        }
    }

    // display  picture in its own window
    pictureR.show();

  }

}

它按预期工作。 input Image

Output image

现在我想将整个图像的颜色设置为rgb 255,153,51。我试着设置 pictureR.set(col, row, new Color(255, 153, 51))。但结果输出是下面的图像resulting image

如何获得正确的图像?请帮忙。

1 个答案:

答案 0 :(得分:5)

您最初的例子误导了您。您在第一个示例中的代码是设置不同的红色阴影(从原始红色通道拉出),创建“红色”图像,而不是像您认为的那样“着色”图像。

int r = color.getRed();
pictureR.set(col, row, new Color(r, 0, 0));

你的第二个例子是为每个像素设置一个固定的颜色,这样你就可以获得均匀的橙色。

pictureR.set(col, row, new Color(255, 153, 51))

您需要通过改变所有三个通道来着色图像,就像您最初改变红色值一样。有关使用合成的示例,请参阅this question,这与您现在使用的角度不同。

根据您的示例代码,最简单的实现方法是计算每个像素的relative luminence(实际上是灰度值)并使用它来调整您设置的“橙色”值。 luminence的标准权重是

L = 0.2126*R + 0.7152*G + 0.0722*B

类似

pictureR.set(col, row, new Color(255 * L/255, 153 * L/255, 51 * L/255));