怎么用java将png图片转换成jpg格式的图片

摘要: png是一种背景透明格式的图片,大量用于网络上,保真性很好,JPG是压缩图片,占用空间少。但有一些失真,所以在将png图片转换成jpg图片之后,肯定是有一些差异的,毕竟这是两种不同的格式.

png是一种背景透明格式的图片,大量用于网络上,保真性很好,JPG是压缩图片,占用空间少。但有一些失真,所以在将png图片转换成jpg图片之后,肯定是有一些差异的,毕竟这是两种不同的格式.

下面用一个例子将一个透明的png转换成背景为白色的jpg图片

import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
 
public class ConvertImageFile {
 
   public static void main(String[] args) {
 
	BufferedImage bufferedImage;
 
	try {
 
	  //read image file
	  bufferedImage = ImageIO.read(new File("c:\\java.png"));
 
	  // create a blank, RGB, same width and height, and a white background
	  BufferedImage newBufferedImage = new BufferedImage(bufferedImage.getWidth(),
			bufferedImage.getHeight(), BufferedImage.TYPE_INT_RGB);
	  newBufferedImage.createGraphics().drawImage(bufferedImage, 0, 0, Color.WHITE, null);
 
	  // write to jpeg file
	  ImageIO.write(newBufferedImage, "jpg", new File("c:\\java.jpg"));
 
	  System.out.println("Done");
 
	} catch (IOException e) {
 
	  e.printStackTrace();
 
	}
 
   }
 
}

上一篇: jquery 的一些好插件
下一篇: JAVA 单例模式与hashmap结合实现缓存

Avatar

美工阿威 评论于: 2015-10-04

不错,比stackoverflow上的多数答案更简洁靠谱。
回馈两方法:
public static BufferedImage toOpaqueImage(BufferedImage input){
		return toOpaqueImage(input,Color.WHITE);
	}
	public static BufferedImage toOpaqueImage(BufferedImage input,Color bgColor){
		BufferedImage output=new BufferedImage(input.getWidth(), input.getHeight(), BufferedImage.TYPE_INT_RGB);
		output.createGraphics().drawImage(input, 0, 0, input.getWidth(), input.getHeight(), bgColor, null);
		return output;
	}
 评论 ( What Do You Think )
名称
邮箱
网址
评论
验证
   
 

 


  • 微信公众号

  • 我的微信

站点声明:

1、一号门博客CMS,由Python, MySQL, Nginx, Wsgi 强力驱动

2、部分文章或者资源来源于互联网, 有时候很难判断是否侵权, 若有侵权, 请联系邮箱:summer@yihaomen.com, 同时欢迎大家注册用户,主动发布无版权争议的 文章/资源.

3、鄂ICP备14001754号-3, 鄂公网安备 42280202422812号