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();
}

你可能感兴趣的:(java)