繁体   English   中英

在Java中更改图像颜色

[英]changing image color in java

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

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();

  }

}

它按预期工作。 输入图像

输出图像

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

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

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

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

第二个示例是为每个像素设置固定的颜色,因此您获得统一的橙色。

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

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

在给定示例代码的情况下,最简单的实现方法是计算每个像素的相对亮度 (实际上是灰度值),然后使用该亮度来调整您设置的“橙色”值。 亮度的标准权重为

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));

暂无
暂无

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

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