失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > 上传文件 压缩临时图片 不做本地图片存储 用于传输

上传文件 压缩临时图片 不做本地图片存储 用于传输

时间:2019-09-16 20:44:34

相关推荐

上传文件 压缩临时图片 不做本地图片存储 用于传输

前端上传的MultipartFile file//创建临时文件OutputStream stream = null;File toFile = null;try {toFile = File.createTempFile("temp_file", ".jpg");toFile.deleteOnExit();stream = new FileOutputStream(toFile);stream.write(file.getBytes());} finally {if (stream != null) {try {stream.close();} catch (IOException e) {// Nothing sane to do}}}/*** 根据指定大小和指定精度压缩图片** @param filefile 文件* @param desFileSize 指定图片大小,单位kb* @param accuracy精度,递归压缩的比率,建议小于0.9* @param desMaxWidth 目标最大宽度* @param desMaxHeight 目标最大高度* @return 目标文件路径*/public static byte[] commpressPicForScale(File file, long desFileSize, double accuracy, int desMaxWidth, int desMaxHeight) throws IOException {long srcFileSize = file.length();//获取图片信息BufferedImage bim = ImageIO.read(file);int srcWidth = bim.getWidth();int srcHeight = bim.getHeight();//先转换成jpgThumbnails.Builder builder = Thumbnails.of(file).outputFormat("jpg");// 指定大小(宽或高超出会才会被缩放)if (srcWidth > desMaxWidth || srcHeight > desMaxHeight) {builder.size(desMaxWidth, desMaxHeight);} else {//宽高均小,指定原大小builder.size(srcWidth, srcHeight);}// 写入到内存ByteArrayOutputStream baos = new ByteArrayOutputStream(); //字节输出流(写入到内存)builder.toOutputStream(baos);// 递归压缩,直到目标文件大小小于desFileSize// 输出到文件return commpressPicCycle(baos.toByteArray(), desFileSize, accuracy);}private static byte[] commpressPicCycle(byte[] bytes, long desFileSize, double accuracy) throws IOException {// File srcFileJPG = new File(desPath);long srcFileSizeJPG = bytes.length;// 2、判断大小,如果小于 xxx kb,不压缩;如果大于等于 xxx kb,压缩if (srcFileSizeJPG <= desFileSize * 1024) {return bytes;}// 计算宽高BufferedImage bim = ImageIO.read(new ByteArrayInputStream(bytes));int srcWdith = bim.getWidth();int srcHeigth = bim.getHeight();int desWidth = new BigDecimal(srcWdith).multiply(new BigDecimal(accuracy)).intValue();int desHeight = new BigDecimal(srcHeigth).multiply(new BigDecimal(accuracy)).intValue();ByteArrayOutputStream baos = new ByteArrayOutputStream(); //字节输出流(写入到内存)Thumbnails.of(new ByteArrayInputStream(bytes)).size(desWidth, desHeight).outputQuality(accuracy).toOutputStream(baos);return commpressPicCycle(baos.toByteArray(), desFileSize, accuracy);}

如果觉得《上传文件 压缩临时图片 不做本地图片存储 用于传输》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。