Java - BufferedImage中的setRGB没有改变为正确的颜色

时间:2017-07-17 02:07:35

标签: java image bufferedimage

我似乎无法让bufferedimage的.setRGB正常工作:

BufferedImage img = null;
try 
{
    img = ImageIO.read(new File("icons/br.jpeg"));
}
catch (IOException e) 
{
}

for(int x = img.getWidth()-1; x >= 0; x--)
{
    for(int y = img.getHeight()-1; y >= 0; y--)
    {
        Color b = new Color(255, 255, 255);
        img.setRGB(x, y, b.getRGB());
    }
}

//Save New Image
File outputfile = new File("icons/newestSave.jpeg");
ImageIO.write(img, "jpeg", outputfile);

这是br.jpeg:http://i.imgur.com/w1dZogA.png

这就是结果:http://i.imgur.com/MVIxiA7.jpg

输出应为纯白色,因为程序应将每个像素更改为255,255,255。

1 个答案:

答案 0 :(得分:0)

您的源图片类型为TYPE_BYTE_INDEXED(使用img.getType()来显示类型),您需要将图像保存为类型:TYPE_3BYTE_BGR

BufferedImage i = null;
BufferedImage img = null;
try 
{
    i = ImageIO.read(new File("icons/br.jpeg"));
    img = new BufferedImage(i.getWidth(),i.getHeight(), BufferedImage.TYPE_3BYTE_BGR);
}
catch (IOException e) 
{
}

//copy the image
img.getGraphics().drawImage(i, 0, 0, null);


for(int x = img.getWidth()-1; x >= 0; x--)
{
    for(int y = img.getHeight()-1; y >= 0; y--)
    {
        Color b = new Color(255, 255, 255);
        img.setRGB(x, y, b.getRGB());
    }
}

//Save New Image
File outputfile = new File("icons/newestSave.jpeg");
ImageIO.write(img, "jpeg", outputfile);