java上传图片压缩大小

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);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值