下载压缩图片

来源:互联网 发布:视频广告制作软件 编辑:程序博客网 时间:2024/06/05 17:26
public static void doFileDownload(String path,
HttpServletResponse response, String filename, int width, int hight)
throws Exception {
// path是指欲下载的文件的路径。
File file = new File(path);
Image img = ImageIO.read(file); // 构造Image对象
int srcwidth = img.getWidth(null); // 得到源图宽
int srcheight = img.getHeight(null); // 得到源图长
// 按照宽度还是高度进行压缩 width 最大宽度 hight 最大高度
if (srcwidth / srcheight > width / hight) {
int h = (int) (srcheight * width / srcwidth);
resize(img, width, h, response, filename, file);
} else {
int w = (int) (srcwidth * hight / srcheight);
resize(img, w, hight, response, filename, file);
}

}


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

* @param w
*            int 新宽度
* @param h
*            int 新高度
*/
public static void resize(Image img, int w, int h,
HttpServletResponse response, String filename, File file)
throws IOException {
// SCALE_SMOOTH 的缩略算法 生成缩略图片的平滑度的 优先级比速度高 生成的图片质量比较好 但速度慢
BufferedImage image = new BufferedImage(w, h,
BufferedImage.TYPE_INT_RGB);
image.getGraphics().drawImage(img, 0, 0, w, h, null); // 绘制缩小后的图
String newFileName = getNewFileName() + ".jpg";
File destFile = new File(imagePath + File.separator + newFileName);
FileOutputStream out = new FileOutputStream(destFile); // 输出到文件流
// 可以正常实现bmp、png、gif转jpg
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
encoder.encode(image); // JPEG编码
out.close();
// 清空response
response.reset();
// 设置response的Header
response.addHeader("Content-Disposition", "attachment;filename="
+ new String(filename.getBytes()));
response.addHeader("Content-Length", "" + destFile.length());
response.setContentType("application/octet-stream");
// 可以正常实现bmp、png、gif转jpg
OutputStream toClient = new BufferedOutputStream(
response.getOutputStream());
// 以流的形式下载文件。
InputStream fis = new BufferedInputStream(new FileInputStream(destFile));
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
toClient.write(buffer);
toClient.flush();
toClient.close();
}

0 0
原创粉丝点击