读入 Bufferedimage 像素值,然后处理每个像素值并写入文件

Read in Bufferedimage pixel values then manipulate each one and write to file

我目前正在尝试逐个像素地读入图像,并将每个彩色像素更改为 (100,100,100) 的 rgb 值。无论出于何种原因,当我检查每个像素的值时,保存图像的所有彩色像素都改为 (46,46,46)。

这是原图

在运行我的程序之后,这是它给我的图像

这是代码

import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;

public class Cmaps {
    public static void main(String[] args){
        File originalImage = new File("C:\Users\Me\Desktop\0005.bmp");
        BufferedImage img = null;
        try{
            img = ImageIO.read(originalImage);
            for(int i = 0; i < img.getHeight(); i++){
                for(int j = 0; j < img.getWidth(); j++){
                    //get the rgb color of the image and store it
                    Color c = new Color(img.getRGB(i, j));
                    int r = c.getRed();
                    int g = c.getGreen();
                    int b = c.getBlue();
                    //if the pixel is white then leave it alone
                    if((r == 255) && (g == 255) && (b == 255)){
                        img.setRGB(i, j, c.getRGB());
                        continue;
                    }
                    //set the colored pixel to 100,100,100
                    r = 100;// red component 0...255
                    g = 100;// green component 0...255
                    b = 100;// blue component 0...255
                    int col = (r << 16) | (g << 8) | b;
                    img.setRGB(i, j, col);
                }
            }
            File f = new File("C:\Users\Me\Desktop\2\1.png");
            try {
                ImageIO.write(img, "PNG", f);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        } catch (IOException e){
            e.printStackTrace();
        }
    }
}

我不知道为什么它没有将像素设置为预期的 rgb 值。我最终希望能够在我向下移动 x 和 y 中的行和列时基本上增加 rgb 颜色,所以最终图像的样子是它将从左上角开始变暗,然后产生淡出效果当你从那一侧到达右下角时。

好的,根据评论:

如果 BufferedImage 有一个 IndexColorModel(基于调色板的颜色模型),使用 setRGB 将像素设置为任意 RGB 值将不起作用。相反,将查找颜色,像素将获得被认为是调色板中最接近匹配的颜色。

BMP、GIF 和 PNG 等格式在使用 ImageIO 读取时都可以使用 IndexColorModel

要将图像转换为 "true color"(Java 中的 DirectColorModelComponentColorModel 都可以),您可以使用:

BufferedImage img; // your original palette image

int w = img.getWidth();
int h = img.getHeight();
BufferedImage trueColor = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);

Graphics2D g = trueColor.createGraphics();
try {
    g.drawImage(img, 0, 0, null);
}
finally {
    g.dispose();
}

img = trueColor;

在此之后,getRGB(x, y) 应该 return 您指定的内容,使用 setRGB(x, y, argb)