java压缩图片

private String doUpload(HttpServletRequest request) throws Exception{
StringBuilder pics = new StringBuilder();
//临时目录
String temp = getServletContext().getRealPath("/")+ "temp";
//上传文件存放目录
String loadpath = getServletContext().getRealPath("/")+ "Image";
//上传文件存放目录
Stringloadpath_target = getServletContext().getRealPath("/")+"Image/target/";

DiskFileUpload fu = new DiskFileUpload();
//设置允许用户上传文件大小,单位:字节
fu.setSizeMax(maxSize);
//设置最多只允许在内存中存储的数据,单位:字节
fu.setSizeThreshold(1024*4);
//设置一旦文件大小超过getSizeThreshold()的值时数据存放在硬盘的目录
fu.setRepositoryPath(temp);

//开始读取上传信息
List fileItems = fu.parseRequest(request);
//依次处理每个上传的文件
Iterator iter = fileItems.iterator();
while(iter.hasNext()){
//忽略其他不是文件域的所有表单信息
FileItem item = (FileItem)iter.next();
if(!item.isFormField()){
//获取上传文件名,包括路径
String name = item.getName();
long size = item.getSize();
if(!CommonUtil.hasSetValue(name)||size<=0){
continue;
}

//从全路径中提取文件名
name = name.substring(name.lastIndexOf("\\") + 1);

int point = name.indexOf(".");
if(point==-1){
point = 0;
}

UUID uuid = UUID.randomUUID();
name = uuid + name.substring(point);
File fNew = new File(loadpath, name);
item.write(fNew);

Image img = ImageIO.read(fNew);
int width_init = img.getWidth(null);
int height_init = img.getHeight(null);

int width_target = 0;
int height_target = 0;
int multiple = 1;
if(size>targetSize){
multiple =
new Double(StrictMath.sqrt(size/targetSize)).intValue();
}

width_target = width_init/multiple;
height_target = height_init/multiple;

CompressPicUtil mypic = new CompressPicUtil();
mypic.compressPic(fNew, loadpath_target, name, width_target, height_target, true);
pics.append(base_url).append(name).append(",");
}
}

if(pics.length()>0){
pics.delete(pics.length()-1, pics.length());
}

return pics.toString();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值