简单的java图片缩小(放大)工具类
这是一个图片缩小放大用的工具类,做网页头像的时候用得到可以不用修改直接拿去用。
package com.ssm.utils;
import java.io.*;
import java.awt.*;
import java.awt.image.*;
import com.sun.image.codec.jpeg.*;
/**
* 等比例缩小图片工具类(也可放大)
* @author chenxin
*
*/
public class ChangeImage{
private String destFile;//图片存储地址
private Image img;//传入图片
private int width;//图片原始宽度
private int height;//图片原始高度
/**
* 输入要转换的文件和输出地址名
* @param fileName
* @param destFile
* @throws Exception
*/
public ChangeImage(String fileName,String destFile) throws Exception {
File _file = new File(fileName); // 读入文件
_file.getName();
if(!(destFile.endsWith(".jpg") || destFile.endsWith(".png")))
throw new Exception("请传入jpg或png格式的图片");
this.destFile = destFile;
img = javax.imageio.ImageIO.read(_file); // 构造Image对象
width = img.getWidth(null); // 得到源图宽
height = img.getHeight(null); // 得到源图长
}
/**
* 按指定宽度和高度缩放
* @param args
*/
@SuppressWarnings("restriction")
public void resize(int w, int h) throws IOException {
try {
BufferedImage image = new BufferedImage(w, h,BufferedImage.TYPE_INT_RGB);
image.getGraphics().drawImage(img, 0, 0, w, h, null); // 绘制缩小后的图
FileOutputStream newimageout = new FileOutputStream(destFile); // 输出到文件流
/*
* JPEGImageEncoder 是一个过滤流,它能将图像缓冲数据编码为 JPEG 数据流。该接口的用户应在 Raster 或
* BufferedImage 中提供图像数据,在 JPEGEncodeParams 对象中设置必要的参数, 并成功地打开
* OutputStream(编码 JPEG 流的目的流)。JPEGImageEncoder 接口可 将图像数据编码为互换的缩略
* JPEG 数据流,该数据流将写入提供给编码器的 OutputStream 中。
*/
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(newimageout);
encoder.encode(image); // 近JPEG编码
newimageout.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
/**
* 按照固定的比例缩放图片
*
* @param t double 比例
* @throws IOException
*/
public void resize(double t) throws IOException {
int w = (int) (width * t);
int h = (int) (height * t);
resize(w, h);
}
/**
* 以宽度为基准,等比例放缩图片
*
* @param w int 新宽度
* @throws IOException
*/
public void resizeByWidth(int w) throws IOException {
int h = (int) (height * w / width);
resize(w, h);
}
/**
* 以高度为基准,等比例缩放图片
*
* @param h int 新高度
* @throws IOException
*/
public void resizeByHeight(int h) throws IOException {
int w = (int) (width * h / height);
resize(w, h);
}
/**
* 按照最大高度限制,生成最大的等比例缩略图
*
* @param w int 最大宽度
* @param h int 最大高度
* @throws IOException
*/
public void resizeFix(int w, int h) throws IOException {
if (width / height > w / h) {
resizeByWidth(w);
} else {
resizeByHeight(h);
}
}
/**
* 获取目标文件名 getDestFile
*/
public String getDestFile() {
return destFile;
}
/**
* 获取图片原始宽度 getSrcWidth
*/
public int getSrcWidth() {
return width;
}
/**
* 获取图片原始高度 getSrcHeight
*/
public int getSrcHeight() {
return height;
}
}