JavaWeb后端自动按比例压缩图片并传输的接口

首先为FileController添加Mapping
 
@RequestMapping(value = "/file/compress/{name}.{suffix}")
	public void downloadFileCompress(HttpServletRequest request, HttpServletResponse response, @PathVariable String name, @PathVariable String suffix){
		log.info("File:收到文件下载请求");
		OutputStream out = null;
		try {
			String fileName = name + "." + suffix;
			//用hash算法得出存储路径
			int hashcode = fileName.hashCode();
			int dir1 = hashcode & 0xf;
			int dir2 = (hashcode & 0xf0) >> 4;
			//拼接文件路径
			String resultPath = ResourceUtils.getFile("").getAbsolutePath() + "/Upload/" + dir1 + "/" + dir2 + "/";
			log.info("File:文件保存路径为:" + resultPath);
			File targetFile = new File(resultPath, fileName);
			if(targetFile.exists()) {
				log.info("File:开始文件传输");
				out = response.getOutputStream();
				ImageCompressUtil.compressToOutputStream(targetFile, out); //将
			} else log.info("File:文件不存在");
		}catch (Exception e) {
			e.printStackTrace();
			log.info("File:文件输出发生错误");
		} finally {
			log.info("File:文件传输成功");
			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

添加ImageCompressUtil并实现文件压缩代码
 
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.math.BigDecimal;

public class ImageCompressUtil {

	public static void compressToOutputStream(File targetFile, OutputStream out) {
		InputStream in = null;
		BufferedImage src = null;
		try {
			int threshold = 1024 * 1024;
			if (targetFile.length() > threshold) {
				BigDecimal rate = new BigDecimal(Math.sqrt(new BigDecimal(threshold).divide(new BigDecimal(targetFile.length()), 10, BigDecimal.ROUND_HALF_UP).doubleValue()));
				in = new FileInputStream(targetFile);
				src = ImageIO.read(in);
				int width = new BigDecimal(src.getWidth()).multiply(rate).intValue();
				int height = new BigDecimal(src.getHeight()).multiply(rate).intValue();
				BufferedImage target = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
				target.getGraphics().drawImage(src.getScaledInstance(width, height, Image.SCALE_SMOOTH), 0, 0, null);
				ImageIO.write(target, "jpg", out);
			} else {
				in = new FileInputStream(targetFile);
				byte[] temp = new byte[1024];
				while(in.read(temp) != -1) out.write(temp);
				out.flush();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
ImageCompressUtil将文件直接输出到OutputStream中,完成图片传输

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值