话不多说,直接上代码
import java.awt.image.BufferedImage;
import java.awt.image.Raster;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class IOUtil {
public static void pgm2png(String src, String dest) throws IOException {
BufferedImage image = ImageIO.read(new File(src));
Raster source = image.getRaster();
int width = image.getWidth();
int height = image.getHeight();
// 创建BufferedImage对象
// BufferedImage image2 = new BufferedImage(width,
// height,BufferedImage.TYPE_BYTE_BINARY);//黑色
BufferedImage image2 = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY);// 灰色
// BufferedImage image2 = new BufferedImage(width, height,
// BufferedImage.TYPE_BYTE_INDEXED);//黄色
image2.setData(source);
// 保存文件
ImageIO.write(image2, "png", new File(dest));
}
}
上述代码中,有几个参数需要在格式转换的时候调整。\
- new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY)的第三个参数,图片格式类型
- ImageIO.write(image2, "png", new File(dest)); 的第二个参数,转换的目标图片格式
网友评论