java上传图片压缩大小方法:
package oms.util;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
public class ImageUtil {
/**
*
* @param f
* 图片所在的文件夹路径
* @param filelist
* 图片路径
* @param ext
* 扩展名
* @param n
* 图片名
* @param w
* 目标宽
* @param h
* 目标高
* @param per
* 百分比
* @throws IOException
*/
public static void Tosmallerpic(File srcFile, String targetFilePath, int w,
int h, float per) throws IOException {
Image src;
src = javax.imageio.ImageIO.read(srcFile); // 构造Image对象
Size size =GetSize(src.getWidth(null), src.getHeight(null), w, h);
BufferedImage tag = new BufferedImage(size.w, size.h,
BufferedImage.TYPE_INT_RGB);
// tag.getGraphics().drawImage(src,0,0,size.w,size.h,null); //绘制缩小后的图
tag.getGraphics().drawImage(
src.getScaledInstance(size.w, size.h, Image.SCALE_SMOOTH), 0, 0,
null);
FileOutputStream newimage = new FileOutputStream(targetFilePath); // 输出到文件流
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(newimage);
JPEGEncodeParam jep = JPEGCodec.getDefaultJPEGEncodeParam(tag);
/* 压缩质量 */
jep.setQuality(per, true);
encoder.encode(tag, jep);
// encoder.encode(tag); //近JPEG编码
newimage.close();
}
static class Size {
public int w;
public int h;
}
public static Size GetSize(int imgWidth, int imgHeight, int maxWidth,
int maxHeight) {
Size size = new Size();
if(imgWidth<maxWidth&&imgHeight<maxHeight){
size.w = imgWidth;
size.h = imgHeight;
return size;
}
double sw = (imgWidth * 1.0) / (maxWidth * 1.0);
double sh = (imgHeight * 1.0) / (maxHeight * 1.0);
if (sw > sh) {
size.w = maxWidth;
size.h = maxWidth * imgHeight / imgWidth;
} else {
size.w = maxHeight * imgWidth / imgHeight;
size.h = maxHeight;
}
return size;
}
}
调用方法:ImageUtil.Tosmallerpic(srcFile, zomPath, 150, 150, (float) 1);