用java生成缩略图

来源:互联网 发布:淘宝店铺设置子账号 编辑:程序博客网 时间:2024/04/29 16:42

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;


import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

/**
 * 同步工具的引擎,执行所有同步操作
 *
 * @author ben, <a href="mailto"zhanghh@risesoft.net">zhanghh@risesoft.net
 *
 */
public final class MakeBreviaryImage {
 public MakeBreviaryImage(){
  
 }
 public static void main(String[] args)throws Exception{
  MakeBreviaryImage make=new MakeBreviaryImage();
  make.createPic(new File("d://111.jpg"),220,60, "d://222.jpg");
 }
 public void createPic(File image, int formatWideth,
   int formatHeight, String savePath) throws Exception {
  File _file = image;// get image file
  Image src = javax.imageio.ImageIO.read(_file); // construct image
  int imageWideth = src.getWidth(null); // get wideth of image
  int imageHeight = src.getHeight(null); // get height of image
  int changeToWideth = 0;
  int changeToHeight = 0;
  // set Breviary image''s size
  if (imageWideth > 0 && imageHeight > 0) {
   // flag=true;
   if (imageWideth / imageHeight >= formatWideth / formatHeight) {
    if (imageWideth > formatWideth) {
     changeToWideth = formatWideth;
     changeToHeight = (imageHeight * formatWideth) / imageWideth;
    } else {
     changeToWideth = imageWideth;
     changeToHeight = imageHeight;
    }
   } else {
    if (imageHeight > formatHeight) {
     changeToHeight = formatHeight;
     changeToWideth = (imageWideth * formatHeight) / imageHeight;
    } else {
     changeToWideth = imageWideth;
     changeToHeight = imageHeight;
    }
   }
  }
  // ---------
  BufferedImage bufferedImage = new BufferedImage(changeToWideth,
    changeToHeight, BufferedImage.TYPE_INT_RGB);
  bufferedImage.getGraphics().drawImage(src, 0, 0, changeToWideth,
    changeToHeight, null); // chage image size
  FileOutputStream out = new FileOutputStream(savePath); // out put the
  // image
  JPEGImageEncoder encoder = null;
  encoder = JPEGCodec.createJPEGEncoder(out);
  encoder.encode(bufferedImage); // like JPEG encoding
  // System.out.print(width+"*"+height);
  out.close();

 }
}

原创粉丝点击