用java產生縮圖

來源:互聯網
上載者:User

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();

 }
}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.