<!--照片压缩-->
<dependency>
<groupId>net.coobird</groupId>
<artifactId>thumbnailator</artifactId>
<version>0.4.13</version>
</dependency>
package org.dlax.utils;
import lombok.extern.slf4j.Slf4j;
import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.geometry.Positions;
import sun.misc.BASE64Encoder;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
/**
* @author l
* @version 1.0
* @PACKAGE_NAME: org.dlax.utils
* @date 2022/3/24 09:46 周四
* 照片处理工具
*/
@Slf4j
public class ThumbnailatorUtils {
/**
* 修改像素,这里改为100px*100px
* @param path //现在路径
* @param newPath //处理过后的路径
* @return
*/
public static boolean modifyPixel(String path,String newPath) {
try {
File fromFile = new File(path);
if(!fromFile.exists()){
Thumbnails.of(fromFile).size(100,100)
.toFile(newPath);
}
return true;
}catch (Exception ex){
log.error("修改像素失败:" + ex.getMessage());
}
return false;
}
public static void main(String[] args) {
String urlpath ="http://ip/dn/photo/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20220324141303.jpg";
Map<String, String> map = base64File(urlpath);
}
/**
*url请求地址转压缩完后,转成base64
* @param urlpath
* @return
*/
public static Map<String, String> base64File(String urlpath) {
Map<String, String> stringMap = new HashMap<>();
//对本地文件命名
String fileName = urlpath.substring(urlpath.lastIndexOf("."), urlpath.length());
String strNetImageToBase64 =null;
try {
//将url转成file文件
File file = getFile(urlpath);
byte [] buf = null;
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
//进行压缩处理
Thumbnails.of(file.getAbsoluteFile()).scale(0.5f).toOutputStream(outputStream);
buf = outputStream.toByteArray();
strNetImageToBase64 = new BASE64Encoder().encode(buf);
byteArrayToFile(buf,"C:\\images\\yansu.jpg");
//计算大小
double vbase64 = base64FileSize(strNetImageToBase64);
log.info("图片大小:"+vbase64);
}catch (Exception ex){
log.error("转成base64失败:" + ex.getMessage());
}
stringMap.put("fileName", fileName);
stringMap.put("strNetImageToBase64", strNetImageToBase64);
return stringMap;
}
/**
* 字节数组写出到图片
* @param src
* @param filePath
*/
public static void byteArrayToFile(byte[] src,String filePath) {
File dest = new File(filePath);
InputStream is = null;
OutputStream os = null;
try {
is = new ByteArrayInputStream(src);
os = new FileOutputStream(dest);
//缓冲容器
byte[] flush = new byte[5];
int len;
while((len=is.read(flush))!=-1) {
os.write(flush,0,len);
}
os.flush();
} catch (IOException e) {
} finally {
try {
if (null != os) {
os.close();
}
} catch (Exception e2) {
}
}
}
/**
* 将url转成file文件
* @param url
* @return
*/
public static File getFile(String url) {
//对本地文件命名
String fileName = url.substring(url.lastIndexOf("."),url.length());
File file = null;
URL urlfile;
InputStream inStream = null;
OutputStream os = null;
try {
String tempFilePath="home/tmpphoto/";
File tempDir = new File( tempFilePath );
//判断文件夹是否存在
if (!tempDir.exists() && !tempDir.isDirectory()) {
//不存在的话,创建文件夹
tempDir.mkdirs();
}
file = File.createTempFile("net_url", fileName,tempDir);
//下载
urlfile = new URL(url);
inStream = urlfile.openStream();
os = new FileOutputStream(file);
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = inStream.read(buffer, 0, 8192)) != -1) {
os.write(buffer, 0, bytesRead);
}
} catch (Exception e) {
log.error("将url转成file文件失败:"+ e.getMessage());
} finally {
try {
if (null != os) {
os.close();
}
if (null != inStream) {
inStream.close();
}
} catch (Exception e) {
log.error("关闭文件失败:"+ e.getMessage());
}
}
return file;
}
/**
* 精确计算base64字符串文件大小(单位:B)
* @param base64String
* @return
*/
public static double base64FileSize(String base64String) {
/**检测是否含有base64,文件头)*/
base64String = base64String.substring(base64String.lastIndexOf(",")+1);
/** 获取base64字符串长度(不含data:audio/wav;base64,文件头) */
int size0 = base64String.length();
/** 获取字符串的尾巴的最后10个字符,用于判断尾巴是否有等号,正常生成的base64文件'等号'不会超过4个 */
String tail = base64String.substring(size0 - 10);
/** 找到等号,把等号也去掉,(等号其实是空的意思,不能算在文件大小里面) */
int equalIndex = tail.indexOf("=");
if (equalIndex > 0) {
size0 = size0 - (10 - equalIndex);
}
/** 计算后得到的文件流大小,单位为字节 */
return size0 - ((double) size0 / 8) * 2;
}
/**
* 按比例缩小
* @param path //现在路径
* @param newPath //处理过后的路径
* @return
*/
public static boolean scaleDown(String path,String newPath) {
try {
File fromFile = new File(path);
if(fromFile.exists()){
Thumbnails.of(fromFile).scale(0.5f)
.toFile(newPath);
return true;
}
}catch (Exception ex){
log.error("按比例缩小失败:" + ex.getMessage());
}
return false;
}
/**
* 尺寸不变,修改文件大小
* @param path //现在路径
* @param newPath //处理过后的路径
* @return
*/
public static boolean modifyFileSize(String path,String newPath) {
try {
File fromFile = new File(path);
if(fromFile.exists()){
Thumbnails.of(fromFile).scale(1).outputQuality(0.2f)
.toFile(newPath);
return true;
}
}catch (Exception ex){
log.error("尺寸不变,修改文件大小失败:" + ex.getMessage());
}
return false;
}
/**
* 加水印,需指定水印图片和透明度
* @param path //现在路径
* @param newPath //处理过后的路径
* @return
*/
public static boolean specifyWatermarkPicture(String path,String newPath) {
try {
File fromFile = new File(path);
if(fromFile.exists()){
Thumbnails.of(fromFile).scale(1).watermark(Positions.BOTTOM_RIGHT, ImageIO.read(fromFile),0.5f)
.toFile(newPath);
return true;
}
}catch (Exception ex){
log.error("加水印,需指定水印图片和透明度失败:" + ex.getMessage());
}
return false;
}
/**
* 加水印,水印为自定义文字
* @param path //现在路径
* @param text //自定义文字
* @param newPath //处理过后的路径
* @return
*/
public static boolean customtext(String text,String path,String newPath) {
try {
File fromFile = new File(path);
if(fromFile.exists()){
BufferedImage bi = new BufferedImage(80,30,BufferedImage.TYPE_INT_BGR);
Graphics2D g = bi.createGraphics();
g.setColor(Color.lightGray);
g.drawRect(0,0,80,30);
g.drawString(text, 15,15);
Thumbnails.of(fromFile).scale(1).watermark(Positions.BOTTOM_RIGHT, bi,0.3f)
.toFile(newPath);
return true;
}
}catch (Exception ex){
log.error("加水印,水印为自定义文字失败:" + ex.getMessage());
}
return false;
}
/**
* 转换图片格式
* @param path //现在路径
* @param newPath //处理过后的路径
* @return
*/
public static boolean convertPictureFormat(String path,String newPath) {
try {
File fromFile = new File(path);
if(fromFile.exists()){
Thumbnails.of(fromFile).scale(1).outputFormat("png")
.toFile(newPath);
return true;
}
}catch (Exception ex){
log.error("转换图片格式失败:" + ex.getMessage());
}
return false;
}
/**
* 图片裁减
* @param path //现在路径
* @param newPath //处理过后的路径
* @return
*/
public static boolean imageReduction(String path,String newPath) {
try {
File fromFile = new File(path);
if(fromFile.exists()){
Thumbnails.of(fromFile).sourceRegion(0, 0, 200, 200).size(200,200)
.toFile(newPath);
return true;
}
}catch (Exception ex){
log.error("图片裁减失败:" + ex.getMessage());
}
return false;
}
}