当前位置:首页 » JAVA技术教程

JAVA图片缩放类

2010-06-02 14:31 本站整理 浏览(14)

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

}

}