public class ImageCompressUtil {
public static void reduceImg(String imgsrc, String imgdist) {
try {
File srcfile = new File(imgsrc);
// 检查图片文件是否存在
if (!srcfile.exists()) {
System.out.println("文件不存在");
}
int[] results = getImgWidthHeight(srcfile);
int widthdist = results[0];
int heightdist = results[1];
// 开始读取文件并进行压缩
Image src = ImageIO.read(srcfile);
// 构造一个类型为预定义图像类型之一的 BufferedImage
BufferedImage tag = new BufferedImage( widthdist, heightdist, BufferedImage.TYPE_INT_RGB);
// 这边是压缩的模式设置
tag.getGraphics().drawImage(src.getScaledInstance(widthdist, heightdist, Image.SCALE_SMOOTH), 0, 0, null);
//创建文件输出流
FileOutputStream out = new FileOutputStream(imgdist);
//将图片按JPEG压缩,保存到out中
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
encoder.encode(tag);
//关闭文件输出流
out.close();
} catch (Exception ef) {
ef.printStackTrace();
}
}
public static void reduceImg(InputStream imgsrc, String imgdist) throws IOException {
Image src = ImageIO.read(imgsrc);
int[] results = getImgWidthHeight(src);
int widthdist = results[0];
int heightdist = results[1];
// 开始读取文件并进行压缩
// 构造一个类型为预定义图像类型之一的 BufferedImage
BufferedImage tag = new BufferedImage( widthdist, heightdist, BufferedImage.TYPE_INT_RGB);
// 这边是压缩的模式设置
tag.getGraphics().drawImage(src.getScaledInstance(widthdist, heightdist, Image.SCALE_SMOOTH), 0, 0, null);
//创建文件输出流
FileOutputStream out = new FileOutputStream(imgdist);
//将图片按JPEG压缩,保存到out中
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
encoder.encode(tag);
//关闭文件输出流
out.close();
imgsrc.close();
}
/**
* 获取图片宽度和高度
*
* @param file 图片路径
* @return 返回图片的宽度
*/
public static int[] getImgWidthHeight(File file) {
InputStream is = null;
BufferedImage src = null;
int result[] = {
0, 0 };
try {
// 获得文件输入流
is = new FileInputStream(file);
// 从流里将图片写入缓冲图片区
src = ImageIO.read(is);
// 得到源图片宽
result[0] =src.getWidth(null);
// 得到源图片高
result[1] =src.getHeight(null);
is.close(); //关闭输入流
} catch (Exception ef) {
ef.printStackTrace();
}
return result;
}
public static int[] getImgWidthHeight(Image image) {
int result[] = {
0, 0 };
try {
// 得到源图片宽
result[0] =image.getWidth(null);
// 得到源图片高
result[1] =image.getHeight(null);
} catch (Exception ef) {
ef.printStackTrace();
}
return result;
}
}
java 压缩图片存储(jpg/png)
猜你喜欢
转载自blog.csdn.net/dndndnnffj/article/details/109641963
今日推荐
周排行