我正在尝试使用RGBImageFilter和FilteredImageSource更改.png文件中的颜色,然后将文件保存到磁盘,它似乎工作正常..但是当我在程序完成后打开新文件时,它看起来就像原版一样,即我刚刚复制了文件。
代码如下所示:
public class ChangeImageColor {
public static void main(String[] args) {
BufferedImage image = null;
try {
image = ImageIO.read(new File("png_test.png") );
ImageFilter colorfilter = new RedBlueSwapFilter();
FilteredImageSource filteredImageSource = new FilteredImageSource(image.getSource(), colorfilter );
Image filteredImage = Toolkit.getDefaultToolkit().createImage(filteredImageSource);
BufferedImage filtered = new BufferedImage(
filteredImage.getWidth(null), filteredImage.getHeight(null),
BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = filtered.createGraphics();
g2.drawImage(image, 0, 0, null);
g2.dispose();
save(filtered, "png");
} catch( IOException e){
//do something
System.out.print(e.getMessage());
}
}
private static void save(BufferedImage image, String ext) {
String fileName = "png_test_manipulated";
File file = new File(fileName + "." + ext);
try {
ImageIO.write(image, ext, file); // ignore returned boolean
} catch(IOException e) {
System.out.println("Write error for " + file.getPath() +
": " + e.getMessage());
}
}
static class RedBlueSwapFilter extends RGBImageFilter {
public RedBlueSwapFilter() {
// The filter's operation does not depend on the
// pixel's location, so IndexColorModels can be
// filtered directly.
canFilterIndexColorModel = true;
}
@Override
public int filterRGB(int x, int y, int rgb) {
/*return ((rgb & 0xff00ff00)
| ((rgb & 0xff0000) >> 16)
| ((rgb & 0xff) << 16));*/
return 0x00000000;
}
}
}
答案 0 :(得分:1)
你的问题:
g2.drawImage(image, 0, 0, null);
使用此代码绘制旧图像,尝试删除以下行:
Graphics2D g2 = filtered.createGraphics();
g2.drawImage(image, 0, 0, null);
g2.dispose();