您的位置:首页 > 其它

工具类:图片压缩处理

2015-10-26 00:00 232 查看
摘要: 图片压缩处理

package com.hengshan.yundonggo.util;

import java.io.*;

import java.awt.*;

import java.awt.image.*;

import javax.imageio.ImageIO;

import com.sun.image.codec.jpeg.*;

/**

* 图片压缩处理

*

* @author dgy

*

*/

public class ImgCompress {

private Image img;

private int width;

private int height;

public static String startCompress(File photo, String username, String imgname) {

String src = null;

try {

ImgCompress imgCom = new ImgCompress(photo);

src = imgCom.resizeFix(400, 400, username, imgname);

} catch (Exception e) {

e.printStackTrace();

}

return src;

}

/**

* 构造函数

*/

public ImgCompress(File photo) throws IOException {

img = ImageIO.read(photo); // 构造Image对象

width = img.getWidth(null); // 得到源图宽

height = img.getHeight(null); // 得到源图长

}

/**

* 按照宽度还是高度进行压缩

*

* @param w

* int 最大宽度

* @param h

* int 最大高度

*/

public String resizeFix(int w, int h, String username, String imgname) throws IOException {

String src;

if (width / height > w / h) {

src = resizeByWidth(w, username, imgname);

} else {

src = resizeByHeight(h, username, imgname);

}

return src;

}

/**

* 以宽度为基准,等比例放缩图片

*

* @param w

* int 新宽度

*/

public String resizeByWidth(int w, String username, String imgname) throws IOException {

int h = (int) (height * w / width);

String src = resize(w, h, username, imgname);

return src;

}

/**

* 以高度为基准,等比例缩放图片

*

* @param h

* int 新高度

*/

public String resizeByHeight(int h, String username, String imgname) throws IOException {

int w = (int) (width * h / height);

String src = resize(w, h, username, imgname);

return src;

}

/**

* 强制压缩/放大图片到固定的大小

*

* @param w

* int 新宽度

* @param h

* int 新高度

*/

@SuppressWarnings("restriction")

public String resize(int w, int h, String username, String imgname) throws IOException {

// SCALE_SMOOTH 的缩略算法 生成缩略图片的平滑度的优先级比速度高生成的图片质量比较好 但速度慢

BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);

image.getGraphics().drawImage(img, 0, 0, w, h, null); // 绘制缩小后的图

// 保存到服务器

String path1 = "E:" + File.separator + "img" + File.separator + username;

File photo = new File(path1);

if (!photo.exists() && !photo.isDirectory()) {

photo.mkdirs();

}

String path = path1 + File.separator + imgname + ".jpg";

File destFile = new File(path);

FileOutputStream out = new FileOutputStream(destFile); // 输出到文件流

// 可以正常实现bmp、png、gif转jpg

JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);

encoder.encode(image); // JPEG编码

out.close();

return username + "/" + imgname + ".jpg";

}

public static void main(String[] args) {

File file = new File("D://hy.jpg");

String src = ImgCompress.startCompress(file, "suoluetu", file.getName());

System.out.println(src);

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  压缩 图片 处理