/*
**************************************************************************
* 版权声明:
**************************************************************************
* 程序描述:
* 图片处理压缩工具
*
**************************************************************************
* 修改历史:
* Date: by: Reason:
*
* 2016年7月18日 Lin.Xu Initial Version.
*************************************************************************
*/
package com.bilfinance.util;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageTypeSpecifier;
import javax.imageio.ImageWriter;
import javax.imageio.metadata.IIOMetadata;
import javax.imageio.plugins.jpeg.JPEGImageWriteParam;
import javax.imageio.stream.ImageOutputStream;
import org.apache.log4j.Logger;
import org.w3c.dom.Element;
/**
* Description:
* 图片处理压缩工具
* @author Lin.Xu
* @date 2016年7月18日
* @version v1.0.0
*/
public class ImageCompressionUtil {
//日志处理对象
private Logger logger = Logger.getLogger(ImageCompressionUtil.class);
//初始化压缩比率
private static float COMPREES_RATIO = 0.38f;
/**
* Description:
* 按照参数默认压缩比率压缩图片操作
* @author Lin.Xu
* @date 2016年7月18日
* @version v1.0.0
* @param originalPath 文件原路径
* @param thumbnailPath 文件目前路径
* @param proportion 是否按照设置压缩 false 不压缩 true 按照设置比例压缩
* @param outWidth 需要压缩的宽度
* @param outHeight 需要压缩的高度
* @return
*/
public boolean compression(String originalPath,String thumbnailPath,
boolean proportion,int outWidth,int outHeight){
boolean boolflg = false;
BufferedImage buffImage = null;
FileOutputStream fileOS = null;
//第一步:获取原始文件信息
try {
File origFile = new File(originalPath);
if(!origFile.exists()){
logger.info("ImageCompressionUtil处理压缩图片未找到源文件信息");
boolflg = false;
}else{
//第二步:读取图片信息
BufferedImage bufimg = ImageIO.read(origFile);
//原始图像的宽度和高度
int width = bufimg.getWidth();
int height = bufimg.getHeight();
//调整后的图片的宽度和高度
int toWidth = width;
int toHeight = height;
if(proportion){
toWidth = 0 == outWidth ? width : outWidth;
toHeight = 0 == outHeight ? height : outHeight;
}
//新生成结果图片
buffImage = new BufferedImage(toWidth, toHeight,BufferedImage.TYPE_INT_RGB);
buffImage.getGraphics().drawImage(bufimg.getScaledInstance(toWidth, toHeight,Image.SCALE_SMOOTH), 0, 0, null);
//第三步:写出图片信息
File outfile = new File(thumbnailPath);
//如果dir对应的文件不存在,或者不是一个目录,则新建
if(!outfile.exists() || !outfile.isDirectory()){
outfile.getParentFile().mkdirs();
}
fileOS = new FileOutputStream(outfile);
//格式化的图片类型
String formatName = thumbnailPath.substring(thumbnailPath.lastIndexOf(".") + 1);
ImageWriter imgaewriter = ImageIO.getImageWritersBySuffix(formatName).next();
ImageOutputStream imageOS = ImageIO.createImageOutputStream(fileOS);
imgaewriter.setOutput(imageOS);
//写入压缩的倍数
JPEGImageWriteParam jpegParams = null;
if(COMPREES_RATIO >= 0 && COMPREES_RATIO <= 1f){
jpegParams = (JPEGImageWriteParam) imgaewriter.getDefaultWriteParam();
jpegParams.setCompressionMode(JPEGImageWriteParam.MODE_EXPLICIT);
jpegParams.setCompressionQuality(COMPREES_RATIO);
}
//清除缓存并写出
imgaewriter.write(null, new IIOImage(buffImage, null, null), jpegParams);
imageOS.close();
imgaewriter.dispose();
boolflg = true;
}
} catch (IOException e) {
logger.info("ImageCompressionUtil处理压缩图片异常:"+e.getMessage());
e.printStackTrace();
}finally{
try {
if(null != fileOS){
fileOS.flush();
fileOS.close();
}
} catch (IOException e) {
logger.info("ImageCompressionUtil处理压缩图片异常:"+e.getMessage());
e.printStackTrace();
}
}
return boolflg;
}
/**
* Description:
* 按照参数压缩图片操作
* @author Lin.Xu
* @date 2016年7月18日
* @version v1.0.0
* @param originalPath 文件原路径
* @param thumbnailPath 文件目前路径
* @param proportion 是否按照设置压缩 false 不压缩 true 按照设置比例压缩
* @param outWidth 需要压缩的宽度
* @param outHeight 需要压缩的高度
* @param quality 指定比率压缩图片信息
* @return
*/
public boolean compression(String originalPath,String thumbnailPath,
boolean proportion,int outWidth,int outHeight,float quality){
boolean boolflg = false;
BufferedImage buffImage = null;
FileOutputStream fileOS = null;
//第一步:获取原始文件信息
try {
File origFile = new File(originalPath);
if(!origFile.exists()){
logger.info("ImageCompressionUtil处理压缩图片未找到源文件信息");
boolflg = false;
}else{
//第二步:读取图片信息
BufferedImage bufimg = ImageIO.read(origFile);
//原始图像的宽度和高度
int width = bufimg.getWidth();
int height = bufimg.getHeight();
//调整后的图片的宽度和高度
int toWidth = width;
int toHeight = height;
if(proportion){
toWidth = 0 == outWidth ? width : outWidth;
toHeight = 0 == outHeight ? height : outHeight;
}
//新生成结果图片
buffImage = new BufferedImage(toWidth, toHeight,BufferedImage.TYPE_INT_RGB);
buffImage.getGraphics().drawImage(bufimg.getScaledInstance(toWidth, toHeight,Image.SCALE_SMOOTH), 0, 0, null);
//第三步:写出图片信息
File outfile = new File(thumbnailPath);
//如果dir对应的文件不存在,或者不是一个目录,则新建
if(!outfile.exists() || !outfile.isDirectory()){
outfile.getParentFile().mkdirs();
}
fileOS = new FileOutputStream(outfile);
//格式化的图片类型
String formatName = thumbnailPath.substring(thumbnailPath.lastIndexOf(".") + 1);
ImageWriter imgaewriter = ImageIO.getImageWritersBySuffix(formatName).next();
ImageOutputStream imageOS = ImageIO.createImageOutputStream(fileOS);
imgaewriter.setOutput(imageOS);
//写入压缩的倍数
JPEGImageWriteParam jpegParams = null;
if(quality >= 0 && quality <= 1f){
jpegParams = (JPEGImageWriteParam) imgaewriter.getDefaultWriteParam();
jpegParams.setCompressionMode(JPEGImageWriteParam.MODE_EXPLICIT);
jpegParams.setCompressionQuality(quality);
}
//清除缓存并写出
imgaewriter.write(null, new IIOImage(buffImage, null, null), jpegParams);
imageOS.close();
imgaewriter.dispose();
boolflg = true;
}
} catch (IOException e) {
logger.info("ImageCompressionUtil处理压缩图片异常:"+e.getMessage());
e.printStackTrace();
}finally{
try {
if(null != fileOS){
fileOS.flush();
fileOS.close();
}
} catch (IOException e) {
logger.info("ImageCompressionUtil处理压缩图片异常:"+e.getMessage());
e.printStackTrace();
}
}
return boolflg;
}
/**
* Description:
* 按照固定分辨和压缩比率参数压缩图片操作
* @author Lin.Xu
* @date 2016年7月18日
* @version v1.0.0
* @param originalPath 文件原路径
* @param thumbnailPath 文件目前路径
* @param proportion 是否按照设置压缩 false 不压缩 true 按照设置比例压缩
* @param outWidth 需要压缩的宽度
* @param outHeight 需要压缩的高度
* @param quality 指定比率压缩图片信息
* @param dpi 指定比率压缩图片信息
* @return
*/
public boolean compression(String originalPath,String thumbnailPath,
boolean proportion,int outWidth,int outHeight,float quality,Integer dpi){
boolean boolflg = false;
BufferedImage buffImage = null;
FileOutputStream fileOS = null;
//第一步:获取原始文件信息
try {
File origFile = new File(originalPath);
if(!origFile.exists()){
logger.info("ImageCompressionUtil处理压缩图片未找到源文件信息");
boolflg = false;
}else{
//第二步:读取图片信息
BufferedImage bufimg = ImageIO.read(origFile);
//原始图像的宽度和高度
int width = bufimg.getWidth();
int height = bufimg.getHeight();
//调整后的图片的宽度和高度
int toWidth = width;
int toHeight = height;
if(proportion){
toWidth = 0 == outWidth ? width : outWidth;
toHeight = 0 == outHeight ? height : outHeight;
}
//新生成结果图片
buffImage = new BufferedImage(toWidth, toHeight,BufferedImage.TYPE_INT_RGB);
buffImage.getGraphics().drawImage(bufimg.getScaledInstance(toWidth, toHeight,Image.SCALE_SMOOTH), 0, 0, null);
//第三步:写出图片信息
File outfile = new File(thumbnailPath);
//如果dir对应的文件不存在,或者不是一个目录,则新建
if(!outfile.exists() || !outfile.isDirectory()){
outfile.getParentFile().mkdirs();
}
fileOS = new FileOutputStream(outfile);
//格式化的图片类型
String formatName = thumbnailPath.substring(thumbnailPath.lastIndexOf(".") + 1);
ImageWriter imgaewriter = ImageIO.getImageWritersBySuffix(formatName).next();
ImageOutputStream imageOS = ImageIO.createImageOutputStream(fileOS);
imgaewriter.setOutput(imageOS);
//添加具体的分辨率
IIOMetadata imageMetaData = imgaewriter.getDefaultImageMetadata(new ImageTypeSpecifier(buffImage), null);
if(dpi != null && !dpi.equals("")){
Element tree = (Element) imageMetaData.getAsTree("javax_imageio_jpeg_image_1.0");
Element jfif = (Element)tree.getElementsByTagName("app0JFIF").item(0);
jfif.setAttribute("Xdensity", Integer.toString(dpi) );
jfif.setAttribute("Ydensity", Integer.toString(dpi));
}
//写入压缩的倍数
JPEGImageWriteParam jpegParams = null;
if(quality >= 0 && quality <= 1f){
//新建压缩比率
jpegParams = (JPEGImageWriteParam) imgaewriter.getDefaultWriteParam();
jpegParams.setCompressionMode(JPEGImageWriteParam.MODE_EXPLICIT);
jpegParams.setCompressionQuality(quality);
}
//清除缓存并写出
imgaewriter.write(imageMetaData, new IIOImage(buffImage, null, null), jpegParams);
imageOS.close();
imgaewriter.dispose();
boolflg = true;
}
} catch (IOException e) {
logger.info("ImageCompressionUtil处理压缩图片异常:"+e.getMessage());
e.printStackTrace();
}finally{
try {
if(null != fileOS){
fileOS.flush();
fileOS.close();
}
} catch (IOException e) {
logger.info("ImageCompressionUtil处理压缩图片异常:"+e.getMessage());
e.printStackTrace();
}
}
return boolflg;
}
/**
* Description:
* 按照自定义分辨率参数压缩图片操作
* @author Lin.Xu
* @date 2016年7月18日
* @version v1.0.0
* @param originalPath 文件原路径
* @param thumbnailPath 文件目前路径
* @param proportion 是否按照设置压缩 false 不压缩 true 按照设置比例压缩
* @param outWidth 需要压缩的宽度
* @param outHeight 需要压缩的高度
* @param dpi 指定分辨率图片信息
* @return
*/
public boolean compression(String originalPath,String thumbnailPath,
boolean proportion,int outWidth,int outHeight,Integer dpi){
boolean boolflg = false;
BufferedImage buffImage = null;
FileOutputStream fileOS = null;
//第一步:获取原始文件信息
try {
File origFile = new File(originalPath);
if(!origFile.exists()){
logger.info("ImageCompressionUtil处理压缩图片未找到源文件信息");
boolflg = false;
}else{
//第二步:读取图片信息
BufferedImage bufimg = ImageIO.read(origFile);
//原始图像的宽度和高度
int width = bufimg.getWidth();
int height = bufimg.getHeight();
//调整后的图片的宽度和高度
int toWidth = width;
int toHeight = height;
if(proportion){
toWidth = 0 == outWidth ? width : outWidth;
toHeight = 0 == outHeight ? height : outHeight;
}
//新生成结果图片
buffImage = new BufferedImage(toWidth, toHeight,BufferedImage.TYPE_INT_RGB);
buffImage.getGraphics().drawImage(bufimg.getScaledInstance(toWidth, toHeight,Image.SCALE_SMOOTH), 0, 0, null);
//第三步:写出图片信息
File outfile = new File(thumbnailPath);
//如果dir对应的文件不存在,或者不是一个目录,则新建
if(!outfile.exists() || !outfile.isDirectory()){
outfile.getParentFile().mkdirs();
}
fileOS = new FileOutputStream(outfile);
//格式化的图片类型
String formatName = thumbnailPath.substring(thumbnailPath.lastIndexOf(".") + 1);
ImageWriter imgaewriter = ImageIO.getImageWritersBySuffix(formatName).next();
ImageOutputStream imageOS = ImageIO.createImageOutputStream(fileOS);
imgaewriter.setOutput(imageOS);
//添加分辨率
IIOMetadata imageMetaData = imgaewriter.getDefaultImageMetadata(new ImageTypeSpecifier(buffImage), null);
if(dpi != null && !dpi.equals("")){
Element tree = (Element) imageMetaData.getAsTree("javax_imageio_jpeg_image_1.0");
Element jfif = (Element)tree.getElementsByTagName("app0JFIF").item(0);
jfif.setAttribute("Xdensity", Integer.toString(dpi) );
jfif.setAttribute("Ydensity", Integer.toString(dpi));
}
//清除缓存并写出
imgaewriter.write(imageMetaData, new IIOImage(buffImage, null, null), null);
imageOS.close();
imgaewriter.dispose();
boolflg = true;
}
} catch (IOException e) {
logger.info("ImageCompressionUtil处理压缩图片异常:"+e.getMessage());
e.printStackTrace();
}finally{
try {
if(null != fileOS){
fileOS.flush();
fileOS.close();
}
} catch (IOException e) {
logger.info("ImageCompressionUtil处理压缩图片异常:"+e.getMessage());
e.printStackTrace();
}
}
return boolflg;
}
public static void main(String[] args) {
String inputFoler = "D:\\weiChar\\file\\upload\\attachment\\2016\\07\\18\\2016071800000008_001_A0001.jpg";
/* 这儿填写你存放要缩小图片的文件夹全地址 */
String outputFolder = "D:\\weiChar\\file\\upload\\attachment\\2016\\07\\18\\2016071800000008_001_A0001_comprs.jpg";
/* 这儿填写你转化后的图片存放的文件夹 */
ImageCompressionUtil imgcomp = new ImageCompressionUtil();
System.out.println(imgcomp.compression(inputFoler, outputFolder, false, 0,0,0.1f,10));
}
}
废话不多说,直接上代码,有写的不对地方请多多指教,建议在实际压缩的过程中使用分辨率和压缩比率同时使用,压缩效果更佳,否则单一操作对于有些图片回导致增大。