图片大小压缩

package com.baosight.ec.userCenter.seller.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.upload.FormFile;

import com.baosight.ec.common.Constants;
import com.baosight.ec.common.EcBaseAction;
import com.baosight.web.struts.BActionContext;
import com.bsteel.exchange.client.common.util.PropertiesUtil;
/**

  • 图片管理 *
  • @author
  • @date 2013-11-1 下午2:23:52
    */
    public class ImgManageAction extends EcBaseAction {

    @Override
    public ActionForward doDefault(BActionContext context) throws Exception {
    // TODO Auto-generated method stub
    return null;
    }

    /*

    • 图片上传
      */
      @SuppressWarnings("unchecked")
      public void uploadImg(BActionContext context) throws IOException{
      ActionForm beanForm = context.getForm();
      String msg = "";
      String path = "";
      StringBuilder json = new StringBuilder();

      Hashtable fileh = beanForm.getMultipartRequestHandler().getFileElements();
      List fileList= new ArrayList();
      for (Iterator it = fileh.keySet().iterator(); it.hasNext();) {
      String key = it.next();
      FormFile formfile = fileh.get(key);
      if(formfile.getFileSize()>0){
      fileList.add(formfile);
      }
      }
      if(fileList.size()>0){
      FormFile file = fileList.get(0);
      if(file!=null){
      int i = file.getFileSize();
      if(file.getFileSize()<=500*1024){
      try {
      path = upload(fileList.get(0));
      msg = "上传成功";
      } catch (Exception e) {
      msg = "错误:"+e.getMessage();
      }
      }else{
      msg = "tooLarge";
      }

      }
      

      }

      json.append("{path:'"+path+"',msg:'"+msg+"'}");

      context.getResponse().setContentType("text/html;charset=UTF-8");
      PrintWriter printWriter = context.getResponse().getWriter();
      printWriter.write(json.toString());
      printWriter.flush();
      printWriter.close();

    }

    private String upload(FormFile file) throws IOException{
    String serverFileName ="";
    if(file!=null){
    //ResourceBundle rb = ResourceBundle.getBundle(Constants.SYSTEM.PROPERTIES_FILE);
    String filePath = Constants.IMAGE_UPLOAD_PATH;
    //本机测试用的路径,不上传
    //filePath="D:\upload\";
    System.out.println("========filePath======="+filePath);
    //String runFlag = rb.getString("run.flag");//标识是在哪台服务器上运行(a:103,b:68)
    //System.out.println("此服务器的运行标识是:=========》"+runFlag+"<==========");

        //判断要上传的文件目录是否存在,如果不存在则创建目录
        File tempfile = new File(filePath);
        if(!tempfile.exists()){
            tempfile.mkdir();
        }
    
        //图片上传服务器
        String path = null;
        String localFileName =file.getFileName();
        serverFileName = System.currentTimeMillis()+localFileName.substring(localFileName.lastIndexOf("."));
        path = filePath+serverFileName;
    
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(path);
            fos.write(file.getFileData());
            fos.flush();
            fos.close();
    
           System.out.println("FTP服务器传送文件开始!!!");
           boolean transFlag=this.transFile(path,serverFileName);
           if(transFlag){//传送成功后,删除原路径的文件
               boolean deleFlag=new File(path).delete();
               if(deleFlag){
                   System.out.println("文件:====>"+path+"<====删除成功!");
               }                       
           }else {//上传文件失败
            System.out.println("文件:====>"+path+"<====上传失败!");
           }
    
        } catch (Exception e) {
            e.printStackTrace();
        } finally{//关闭资源
            if(fos!=null){
                fos.close();
            }           
        }
    }
    return serverFileName;
    

    }
    /**

    • 将本地服务器的文件传输到目标服务器指定目录
    • @param path 本地服务器的文件名(完整路径)
    • @param serverFileName 根据系统时间重命名的文件名
    • @throws SocketException
    • @throws IOException
      */
      private boolean transFile(String path, String serverFileName) throws SocketException, IOException {
      //判断文件是否传送成功的标识
      boolean result=false;

      String ftpAddress = Constants.FTP_ADDRESS;
      String ftpUser = Constants.FTP_USER;
      String ftpPassword = Constants.FTP_PASSWORD;
      String imageTargetDir = Constants.FTP_TARGETDIR;
      //测试用的URL和路径
      //ftpAddress="10.60.17.145";
      //imageTargetDir="/export/home/jboss/jboss/jboss-3.2/server/default/deploy/webdocs.war/baozypj/upload_image/";
      System.out.println("========ftpAddress======="+ftpAddress);
      System.out.println("========ftpUser======="+ftpUser);
      System.out.println("========ftpPassword======="+ftpPassword);
      System.out.println("========imageTargetDir======="+imageTargetDir);
      FTPClient ftp=new FTPClient();
      ftp.connect(ftpAddress);//连接服务器
      ftp.login(ftpUser, ftpPassword);//登录
      //判断连接是否成功
      int reply=ftp.getReplyCode();
      if(!FTPReply.isPositiveCompletion(reply)){
      System.out.println("连接失败");
      ftp.disconnect();
      return false;
      }

      //String workPath = filePath;//工作目录名
      String workPath = imageTargetDir;
      String remoteFileName=imageTargetDir+serverFileName;//远程文件名
      Boolean b=ftp.changeWorkingDirectory(workPath);//设置工作目录
      System.out.println("目标服务器文件名(全路径):=======>"+remoteFileName+"<==========");

      //FileInputStream fis2=new FileInputStream(path);
      File remoteFile=new File(path);//以本地服务器的文件作为输入流
      //System.out.println("文件的大小为:"+remoteFile.length());
      FileInputStream fis2=new FileInputStream(remoteFile);
      ftp.setFileType(FTP.BINARY_FILE_TYPE);
      if(b){
      Boolean b2=ftp.storeFile(new String(remoteFileName.getBytes(),"iso-8859-1"), fis2);
      if(b2){
      System.out.println("上传成功!图片的大小为:"+remoteFile.length()+"字节");
      if(remoteFile.length()>0){
      result=true;
      }

      }
      fis2.close();
      ftp.logout();

      }
      return result;

      }

    /*

    • 本地图片删除 */ public void deletePic(BActionContext context) throws IOException { // ResourceService resourceService = (ResourceService)context.findService("resourceService", ResourceService.class); String filePath = Constants.IMAGE_UPLOAD_PATH; String imgName = context.getRequest().getParameter("imgName"); String msg = ""; boolean r = false; File file = new File(filePath+imgName); if(file.exists()){ r = file.delete(); if(r){ // resourceService.deleteResourceImgByImgName(imgName); msg = "0"; }else{ msg = "删除错误"; } } context.getResponse().setContentType("text/html;charset=UTF-8"); PrintWriter printWriter = context.getResponse().getWriter(); printWriter.write(msg); }

}
这是我这里的图片上传代码
我想在上传代码哪里的判断图片大于500KB的方法里加入一个图片压缩方法,当图片大于500KB进入此方法进行压缩为更小的KB,然后返回处理过的图片在进入上传图片方法上传!请问代码怎么写

package com.kay.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import java.awt.image.BufferedImage;
import java.awt.Image;
import java.awt.image.AffineTransformOp;
import javax.imageio.ImageIO;
import java.awt.geom.AffineTransform;

public class ImageModify {
/**
* @param filePath
* 图片的原始目录
* @param dirPath
* 处理后的图片存放目录
* @param file
* 原始图片
* @param dirName
* 处理后的图片文件名前缀
* @throws Exception
*
*/
public static void main(String []args) throws Exception{
// ImageModify m=new ImageModify();
// String filePath="f://image";
// String dirPath="f://image";
// String file="a.gif";
// String dirName="img"+(new Date()).getTime();
// if(m.modify(filePath,dirPath,file,dirName)){
// System.out.println("图像处理成功!");
// }
}
public static void modify(String filePath,String dirPath,String file,String dirName) throws Exception {
// ext是图片的格式 gif JPG 或png
String ext = "";
double Ratio = 0.0;
File F = new File(filePath, file);

// if (!F.isFile())
// throw new Exception(F
// + " is not image file error in CreateThumbnail!");
// 首先判断上传的图片是gif还是JPG ImageIO只能将gif转换为png
// if (isJpg(imgfile)) {
// ext = "jpg";
// } else {
ext = "jpg";
// }
File dir=new File(dirPath);
if(!dir.exists()){
dir.mkdir();
}
File ThF = new File(dirPath, dirName);
if(!ThF.exists()){
ThF.createNewFile();
}
BufferedImage Bi = ImageIO.read(F);
// 假设图片宽 高 最大为120 120
Image Itemp = Bi.getScaledInstance(120, 120, Bi.SCALE_SMOOTH);
if ((Bi.getHeight() > 120) || (Bi.getWidth() > 120)) {
if (Bi.getHeight() > Bi.getWidth())
Ratio = 120.0 / Bi.getHeight();
else
Ratio = 120.0 / Bi.getWidth();
}
AffineTransformOp op = new AffineTransformOp(AffineTransform
.getScaleInstance(Ratio, Ratio), null);
Itemp = op.filter(Bi, null);
try {
ImageIO.write((BufferedImage) Itemp, ext, ThF);
} catch (Exception ex) {
throw new Exception(" ImageIo.write error in CreatThum.: "
+ ex.getMessage());
}
// return (true);
}

public static void upload(File file, String fileName, String path) throws IOException{
    InputStream is = null;
    OutputStream os = null;
    try
    {
        File dir = new File(path);
        if (!dir.exists())
        {
            dir.mkdirs();
        }
        if (!file.exists())
        {
            file.createNewFile();
        }
        is = new FileInputStream(file.toString());

        String name = fileName.trim().toString();// 得到上传文件的原名称
        File destFile = new File(path, name);

        os = new FileOutputStream(destFile);

        byte[] buffer = new byte[400];

        int length = 0;

        while ((length = is.read(buffer)) > 0)
        {
            os.write(buffer, 0, length);
        }

    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
    finally
    {
        is.close();
        os.close();
    }

}

}
不晓得这个是不是你要的效果