最近遇到一些需求,需要对图片做格式转化,比如将png图片转为jpeg,或者将jpeg转为png,网上有部分代码,但是发现有些是不正确的,
毕竟png是4通道,32位,而jpeg是3通道,24位,因此两个图片之间转化时,肯定需要注意这些问题,而不是简单的图片内容的转化。
下面小编是小编亲测实用的java方法:
public class ImageConvert { private static final String IMAGE_PATH_PNG = "F:\Gis开发\学习资料\tile\3_0_1.png"; private static final String IMAGE_PATH_PNG_NEW = "F:\Gis开发\学习资料\tile\3_0_1_new.png"; private static final String IMAGE_PATH_JPEG = "F:\Gis开发\学习资料\tile\3_0_1.jpg"; private static final String IMAGE_PATH_JPEG_NEW = "F:\Gis开发\学习资料\tile\3_0_1_new.jpg"; public static void main(String[] args) { png2jpeg(); } public static void png2jpeg() { //读取图片 FileOutputStream fos =null; try { BufferedImage bufferedImage = ImageIO.read(new File(IMAGE_PATH_PNG)); //转成jpeg、 BufferedImage bufferedImage1 = new BufferedImage(bufferedImage.getWidth(), bufferedImage.getHeight(), BufferedImage.TYPE_INT_RGB); bufferedImage1.createGraphics().drawImage(bufferedImage,0,0, Color.white,null); fos = new FileOutputStream(IMAGE_PATH_JPEG_NEW); ImageIO.write(bufferedImage,"jpg",fos); fos.flush(); } catch (IOException e) { e.printStackTrace(); try { fos.close(); } catch (IOException ioException) { ioException.printStackTrace(); } } } public static void jpeg2png() { //读取图片 try { BufferedImage bufferedImage = ImageIO.read(new File(IMAGE_PATH_JPEG)); //转成png、 BufferedImage bufferedImage1 = new BufferedImage(bufferedImage.getWidth(), bufferedImage.getHeight(), BufferedImage.TYPE_INT_ARGB); bufferedImage1.createGraphics().drawImage(bufferedImage,0,0, Color.white,null); FileOutputStream fos = new FileOutputStream(IMAGE_PATH_PNG_NEW); ImageIO.write(bufferedImage1,"png",fos); } catch (IOException e) { e.printStackTrace(); } } }