java 图片压缩

public class ImageUtil {
 /**
  * 图片转换功能
  *
  * @param widt  int          目标图片宽度
  * @param height
  *            int         目标图片高度
  * @param fromDir
  *            String       源文件夹
  * @param fromFile
  *            String      源文件名
  * @param toDir
  *            String        目标文件夹
  * @param toSmallFile
  *            String     目标文件名
  * @param chanageFormat
  *            String    JPG PNG BMP GIF
  * @param ratioType
  *            int        为0时受比例限制,为1时不受比例限制强行按给定尺寸进行转换
  * @param isFromFileDel
  *            int      0表示不删除原文件,1表示删除原文件;
  * @return int             1成功0失败
  */
 @SuppressWarnings("static-access")
 public int SmallPic(File f) {
  try {
   
   String fromFile=f.getName();
   String fromDir=f.getParent();
   int num = fromFile.lastIndexOf(".");
   String a = fromFile.substring(num+1);
   String toDir=fromDir;
   String toSmallFile=fromFile.substring(0,num)+"suoxiao."+a;
   int isFromFileDel=0;//是否是删除原始图片
   int ratioType=1;//为0时受比例限制,为1时不受比例限制强行按给定尺寸进行转换
   int width = 72;
   int height = 72;
   String Imagetype = a;
   File fF = new File(fromDir, fromFile);
   File tF = new File(toDir, toSmallFile);
   BufferedImage bi = ImageIO.read(fF);
          
   int pwidth = (int) (bi.getWidth());
   int pheight = (int) (bi.getHeight());
   double ratioX = 1.0000;
   double ratioY = 1.0000;
   Image Itemp = bi.getScaledInstance(width, height, bi.SCALE_SMOOTH);

   if (ratioType != 1) {
    if ((pwidth > width) || (pheight > height)) {
     double ratioO = 1.0000;
     double ratioN = 1.0000;
     ratioO = (double) height / width;
     ratioN = (double) pheight / pwidth;
     double Nheight = 0;
     double Nwidth = 0;
     if (ratioN > ratioO) {
      // 超高的
      Nheight = height;
      Nwidth = height / ratioN;
     } else {
      // 超宽
      Nwidth = width;
      Nheight = width * ratioN;
     }
     ratioX = Nwidth / pwidth;
     ratioY = Nheight / pheight;

    }
   } else {
    ratioX = (double) width / pwidth;
    ratioY = (double) height / pheight;
    // ratioX=0.55;
    // ratioY=0.43;

   }
   AffineTransformOp op = new AffineTransformOp(AffineTransform
     .getScaleInstance(ratioX, ratioY), null);
   Itemp = op.filter(bi, null);
   ImageIO.write((BufferedImage) Itemp, Imagetype, tF);
   //int fFlen = (int) fF.length();
   if (isFromFileDel == 1) {
    fF.delete();
   }
   return 1;
  } catch (Exception e) {

   /*
    * Log log = Log.getInstance(); log.Addlog(
    * "Mobile转换图片出错(mobileImage.chanageMobPic.SmallPica): " +
    * e.getMessage());
    */

   e.printStackTrace();
   return 0;
  }
 }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值