Java实现bmp和jpeg图片格式互转

Java实现bmp和jpeg图片格式互转

Bmp转Jpeg

public static String bmp2Jpeg(String filePath, String outPath) {
	try {
		long start = System.currentTimeMillis();
		// 加载bmp图片
		File file = new File(filePath);
		Image img = ImageIO.read(file);
		BufferedImage tag = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_RGB);
		tag.getGraphics().drawImage(img.getScaledInstance(img.getWidth(null), img.getHeight(null), Image.SCALE_SMOOTH), 0, 0, null);

		// 输出为Jpeg
		FileOutputStream out = new FileOutputStream(outPath);
		// JPEGImageEncoder可适用于其他图片类型的转换
		JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
		encoder.encode(tag);
		out.close();
		
		log.info("bmp 转 JPEG,共耗时:  " + (System.currentTimeMillis() - start) + " 毫秒");
		return outPath;
	} catch (IOException e) {
		e.printStackTrace();
	}
		return outPath;
	}

Jpeg转Bmp

public static void jpeg2Bmp(String inputPath, String outputPath) {
	try {
		long start = System.currentTimeMillis();
	
		// 加载Jpeg图片资源
		FileImageInputStream fiis = new FileImageInputStream(new File(inputPath));
		FileImageOutputStream fios = new FileImageOutputStream(new File(outputPath));
		ImageReader jpegReader = null;
		Iterator<ImageReader> it1 = ImageIO.getImageReadersByFormatName("jpeg");
		if (it1.hasNext()) {
		    jpegReader = it1.next();
		}
		jpegReader.setInput(fiis);
		
		ImageWriter bmpWriter = null;
		Iterator<ImageWriter> it2 = ImageIO.getImageWritersByFormatName("bmp");
		if (it2.hasNext()) {
		    bmpWriter = it2.next();
		}
		bmpWriter.setOutput(fios);
		BufferedImage br = jpegReader.read(0);
		bmpWriter.write(br);
		fiis.close();
		fios.close();
		
		log.info("jpeg 转 bmp,共耗时:" + (System.currentTimeMillis() - start) + " 毫秒");
	} catch (IOException e) {
		e.printStackTrace();
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值