用java转换图片格式(不是修改后缀名),png转jpg时遇到一个问题,图片发生颜色失真,白色背景变成橘红色,加两句代码就可以解决这个问题。
开始的图片转换方法:
public static void converter(File imgfile,String format,File formatFile) throws IOException{
imgfile.canRead();
BufferedImage bi = ImageIO.read(imgfile);
ImageIO.write(bi, format, formatFile);
}
public static void main(String[] args) throws Exception {
ImageUtils.converter(new File("E:\\图片1.png"),"jpg",new File("E:\\图片2.jpg"));
}
修改后的图片转换方法:
public static void converter(File imgfile,String format,File formatFile) throws IOException{
imgfile.canRead();
BufferedImage bi = ImageIO.read(imgfile);
// create a blank, RGB, same width and height, and a white background
BufferedImage newBufferedImage = new BufferedImage(bi.getWidth(), bi.getHeight(), BufferedImage.TYPE_INT_RGB);
newBufferedImage.createGraphics().drawImage(bi, 0, 0, Color.WHITE, null);
ImageIO.write(newBufferedImage, format, formatFile);
}
public static void main(String[] args) throws Exception {
ImageUtils.converter(new File("E:\\图片1.png"),"jpg",new File("E:\\图片2.jpg"));
}