JAVA图片缩放类

import java.awt.Color;
import java.awt.Graphics;
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;

public class Resize_Image {

 public  String  generatethumbnail(String fromurl,String tourl,String name,int width,int height){
     try {
       //新建原始图片输入流
      File _file = new File(fromurl);
      //DataInputStream in = new DataInputStream(new FileInputStream(_file));
      // 构造Image对象
      Image src = javax.imageio.ImageIO.read(_file);
//      float rate = /src.getHeight(null);
      int w = src.getWidth(null);
      int h = src.getHeight(null);
//      int newheight
//      if((int) (h * width/w)<142){
//       newheight = 142;
//      }
//      int newheight = (int) (h * width/w)<142?142:(int) (h * width/w);
      int newheight = height;
      //新建一个画布对象
      BufferedImage tag = new BufferedImage(width, newheight,BufferedImage.TYPE_INT_RGB);
      //绘制缩小后的图
      Graphics g = tag.getGraphics();
      g.setColor(Color.white);
      g.drawImage(src, 0, 0, width, newheight, null);
      //新建输出流对象
      FileOutputStream out = new FileOutputStream(tourl+File.separator+name);
      File f = new File(tourl+File.separator+name);
      boolean flag = true;
      //自动创建多节目录
      if(!f.getParentFile().exists()){
       if(!f.getParentFile().mkdirs()){
        flag = false;
       }else{
        if(!f.exists()){
         if(f.createNewFile()){
          flag = true;
         }else{
          flag = false;
         }
        }
       }
      
      } 
      //对输出流用jpeg编码
      JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
      encoder.encode(tag);
      out.close();
      return name;
     
     
     } catch (Exception e) {
      e.printStackTrace();
      return null;
     }
    }
 
 public static void main(String[] args) {
  Resize_Image r = new Resize_Image();
  r.generatethumbnail("c://001_25.gif", "c://", "right.gif", 17, 17);
 }

}

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值