用Java给您的图片瘦身之Thumbnailator技术(缩略图)

https://blog.csdn.net/yelangkingwuzuhu/article/details/127151913

 

 

package com.huaze.form.util;

import lombok.SneakyThrows;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.io.FilenameUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.Base64;

public class Thumbnailator {

@SneakyThrows
public static String compression(MultipartFile file) {
return compression(file.getInputStream(), file.getOriginalFilename());
}

@SneakyThrows
public static String compression(InputStream inputStream, String fileName) {

// 获取扩展名
String extName = FilenameUtils.getExtension(fileName);

if (!FileUtil.isImg(extName)){
return "";
}

long size = inputStream.available();
// 目标压缩大小 默认60K, base64大概6k
long target = 60000;

// 小于目标大小 直接返回base64
if (size < target) {
return inputStream2Base64(inputStream);
}

// 计算压缩比例
double scale = new BigDecimal(target).divide(new BigDecimal(size), 2, BigDecimal.ROUND_HALF_UP).doubleValue();
// 如果比例实在太大,默认给0.01
if (scale <= 0) {
scale = 0.01;
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
// 压缩
Thumbnails.of(inputStream).scale(scale).toOutputStream(baos);
// 转成base64
String small = outputStream2Base64(baos);

return small;
}


public static String outputStream2Base64(ByteArrayOutputStream swapStream) throws Exception {
byte[] data = swapStream.toByteArray();
return Base64.getEncoder().encodeToString(data);
}

public static String inputStream2Base64(InputStream is) throws Exception {
byte[] data = null;
try {
ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
byte[] buff = new byte[100];
int rc = 0;
while ((rc = is.read(buff, 0, 100)) > 0) {
swapStream.write(buff, 0, rc);
}
data = swapStream.toByteArray();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
throw new Exception("输入流关闭异常");
}
}
}

return Base64.getEncoder().encodeToString(data);
}

}



package com.huaze.form.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;


@Component
@Slf4j
public class FileUtil {

// 图片 扩展名
private static final String[] IMG = {"jpg", "jpeg","png", "bmp", "tif", "gif"};

public static boolean isImg(String extName) {
List arr = CollectionUtils.arrayToList(IMG);
// 扩展名统一转小写处理
extName = extName.toLowerCase();
return arr.contains(extName);
}

/**
* 下载文件名重新编码
*
* @param response 响应对象
* @param realFileName 真实文件名
*/
public static void setAttachmentResponseHeader(HttpServletResponse response, String realFileName) throws UnsupportedEncodingException
{
String percentEncodedFileName = percentEncode(realFileName);
StringBuilder contentDispositionValue = new StringBuilder();
contentDispositionValue.append("attachment; filename=")
.append(percentEncodedFileName)
.append(";")
.append("filename*=")
.append("utf-8''")
.append(percentEncodedFileName);

response.addHeader("Access-Control-Expose-Headers", "Content-Disposition,download-filename");
response.setHeader("Content-disposition", contentDispositionValue.toString());
response.setHeader("download-filename", percentEncodedFileName);
}

public static void setAttachmentResponseHeaderDecode(HttpServletResponse response, String realFileName)
{
StringBuilder contentDispositionValue = new StringBuilder();
contentDispositionValue.append("attachment; filename=")
.append(realFileName)
.append(";")
.append("filename*=")
.append("utf-8''")
.append(realFileName);

response.addHeader("Access-Control-Expose-Headers", "Content-Disposition,download-filename");
response.setHeader("Content-disposition", contentDispositionValue.toString());
response.setHeader("download-filename", realFileName);
}

/**
* 百分号编码工具方法
*
* @param s 需要百分号编码的字符串
* @return 百分号编码后的字符串
*/
public static String percentEncode(String s) throws UnsupportedEncodingException
{
String encode = URLEncoder.encode(s, StandardCharsets.UTF_8.toString());
return encode.replaceAll("\\+", "%20");
}


/**
* 转输出流
*
* @param filePath 文件路径
* @param os 输出流
* @return
*/
public static void writeOut(String filePath, OutputStream os) throws IOException
{
File file = new File(filePath);
if (!file.exists())
{
throw new FileNotFoundException(filePath);
}
FileInputStream fis = new FileInputStream(file);
writeOut(fis, os);
}

public static void writeOut(InputStream is, OutputStream os) throws IOException
{
try
{
byte[] b = new byte[1024];
int length;
while ((length = is.read(b)) > 0)
{
os.write(b, 0, length);
}
}
catch (IOException e)
{
throw e;
}
finally
{
os.close();
is.close();
}
}
}


 

 




posted @   20211103  阅读(151)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· AI与.NET技术实操系列(六):基于图像分类模型对图像进行分类
点击右上角即可分享
微信分享提示