JAVA生成【缩略图】方法

来源:互联网 发布:mac invalid argument 编辑:程序博客网 时间:2024/04/25 12:13

/**
  * 创建缩略图片
  *
  * @param orgpath
  * @param filename
  * @return
  * @description: 描述
  */

//此方法对于ssh项目并且针对 上传功能时,非常有用
 public static Boolean createAbbreviateImg(String orgpath, String filename) {
  Boolean flag = true;
  String filetype = orgpath.substring(orgpath.lastIndexOf(".") + 1,
    orgpath.length());
  if ("jpg".equalsIgnoreCase(filetype)
    || "gif".equalsIgnoreCase(filetype)
    || "png".equalsIgnoreCase(filetype)) {
   try {
    Image srcImage = ImageIO.read(new File(orgpath));
    BufferedImage tag = new BufferedImage(380, 230,
      BufferedImage.TYPE_INT_RGB);
    tag.getGraphics().drawImage(srcImage, 0, 0, 380, 230, null);
    String newImage = IMG_Recroad_LOG_PATH + filename;
    FileOutputStream out = new FileOutputStream(newImage);
    JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
    JPEGEncodeParam jep = JPEGCodec.getDefaultJPEGEncodeParam(tag);
    jep.setQuality(1, true);
    encoder.encode(tag, jep);
    srcImage.flush();
    out.close();
   } catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  } else {
   try {

    BufferedImage bis = ImageIO.read(new File(orgpath));
    int width = bis.getWidth();
    int height = bis.getHeight();
    int wantwidth = 80;// 想要的高度
    int wantheight = (wantwidth * height) / width;
    if (wantheight > wantwidth) {
     wantheight = wantwidth;
     wantwidth = (wantheight * width) / height;
    }
    double scalew = (double) wantwidth / width;
    double scaleh = (double) wantheight / height;
    AffineTransform transform = new AffineTransform();
    transform.setToScale(scalew, scaleh);
    AffineTransformOp at = new AffineTransformOp(transform, null);
    BufferedImage bi = new BufferedImage(wantwidth, wantheight,
      BufferedImage.TYPE_3BYTE_BGR);
    at.filter(bis, bi);
    if (filetype.equalsIgnoreCase("jpg")) {
     ImageIO.write(bi, "jpg", new File(IMG_Recroad_LOG_PATH
       + filename));// 存储小图片

    } else if (filetype.equalsIgnoreCase("gif")) {
     ImageIO.write(bi, "gif", new File(IMG_Recroad_LOG_PATH
       + filename));// 存储小图片

    } else if ( filetype.equalsIgnoreCase("png") ){
     ImageIO.write(bi, "png", new File(IMG_Recroad_LOG_PATH+ filename));// 存储小图片
       
    }
      
   } catch (IOException e) {
    e.printStackTrace();
    flag = false;
   }
  }
  return flag;
 }
}

//有哪些地方不懂的给我留言

原创粉丝点击