简单的改变图片大小的java工具类

来源:互联网 发布:美国研究生费用 知乎 编辑:程序博客网 时间:2024/06/05 02:39

简单的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;}}


1 0
原创粉丝点击