等比例图片压缩算法

图片不失真的等比例压缩算法:
算法思想:根据压缩基数和压缩比来压缩原图,生产一张图片效果最接近原图的缩略图。
算法讲解:
public  void  saveMinPhoto(String srcURL,String deskURL,double comBase,double scale){
/*srcURl 原图地址;deskURL 缩略图地址;comBase 压缩基数;scale 压缩限制(宽/高)比例*/
java.io.File srcFile = new java.io.File(srcURL);
Image src = new javax.imageio.ImageIO.read(srcFile);
int srcHeight = src.getHeight(null);
int srcWidth = src.getWidth(null);
int deskHeight = 0;//缩略图高
int deskWidth  = 0;//缩略图宽
double srcScale = (double)srcHeight/srcWidth;
if((double)srcHeight>comBase || (double)srcWidth>comBase){
     if(srcScale>=scale || 1/srcScale>scale){
            if(srcScale>=scale){
                  deskHeight = (int)comBase;
                  deskWidth  = srcWidth*deskHeight/srcHeight;
              }else{
                 deskWidth = (int)comBase ;
                 deskHeight  = srcHeight*deskWidth/srcWidth;
               }

       } else {
         if((double)srcHeight>comBase){
            deskHeight = (int)comBase;
            deskWidth  = srcWidth*deskHeight/srcHeight;
             } else{
                 deskWidth = (int)comBase ;
                 deskHeight  = srcHeight*deskWidth/srcWidth;
              }

          }
      }else {
          deskHeight = srcHeight;
          deskWidth  = srcWidth;

  }
BufferedImage tag = new BufferedImage(deskWidth, deskHeight,
    BufferedImage.TYPE_3BYTE_BGR);
  tag.getGraphics().drawImage(src, 0, 0, deskWidth, deskHeighth, null); //绘制缩小后的图
  FileOutputStream deskImage = new FileOutputStream(deskURL); //输出到文件流
  JPEGImageEncoder encoder = JPEGCodec
    .createJPEGEncoder(deskImage);
  encoder.encode(tag); //近JPEG编码
  deskImage.close();

}

你可能感兴趣的:(算法)