首页 > 编程语言 >用Java给您的图片瘦身之Thumbnailator技术(缩略图)

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

时间:2023-02-23 21:22:22浏览次数:50  
标签:Java String 缩略图 Thumbnailator static new import public append

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();
}
}
}


 

 




标签:Java,String,缩略图,Thumbnailator,static,new,import,public,append
From: https://www.cnblogs.com/l20211103/p/17149462.html

相关文章

  • JavaScript 一元运算符
    <!DOCTYPEhtml><html> <head> <metacharset="UTF-8"> <title></title> <scripttype="text/javascript"> /* *一元运算符,只需要一个操作数 * +......
  • JavaScript 自增和自减
    <!DOCTYPEhtml><html> <head> <metacharset="UTF-8"> <title></title> <scripttype="text/javascript"> /* *自增++ * -通过自增可以使变......
  • JavaScript Null和Undefined
    <!DOCTYPEhtml><html> <head> <metacharset="UTF-8"> <title></title> <scripttype="text/javascript"> /* *Null(空值)类型的值只有一个,就是null ......
  • JavaScript 强制类型转换
    <!DOCTYPEhtml><html> <head> <metacharset="UTF-8"> <title></title> <scripttype="text/javascript"> /* *强制类型转换 * -指将一个数据......
  • JavaScript 转换为Number
    <!DOCTYPEhtml><html> <head> <metacharset="UTF-8"> <title></title> <scripttype="text/javascript"> /* *将其他的数据类型转换为Number * ......
  • JavaScript 其他进制的数字
    <!DOCTYPEhtml><html> <head> <metacharset="UTF-8"> <title></title> <scripttype="text/javascript"> vara=123; /* *在js中,如果需要......
  • JavaScript 转换为Boolean
    <!DOCTYPEhtml><html> <head> <metacharset="UTF-8"> <title></title> <scripttype="text/javascript"> /* *将其他的数据类型转换为Boolean *......
  • JavaScript 运算符
    <!DOCTYPEhtml><html> <head> <metacharset="UTF-8"> <title></title> <scripttype="text/javascript"> /* *运算符也叫操作符 * 通过运算符......
  • JavaFX相关问题--在使用JavaFX加载本地图片时图片会无法显示
    开发环境及开发工具Eclipse+JDK10问题描述在使用JavaFX加载本地图片时图片会无法显示解决方案解决方法1——使用file:+绝对路径解决方法2——使用相对......
  • LeetCode-14. 最长公共前缀(java)
    一、前言:......