package org.jeecg.modules.staff.utils;
/**
* @className: PicUtils
* @description: TODO 类描述
* @author: HeLei
* @date: 2023/07/10 15:38
* @Company: Copyright© [2023] by [HeLei]
**/
import lombok.extern.slf4j.Slf4j;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Random;
/**
* 图片处理类
*
* @author yyq
*/
@Slf4j
public class PicUtils {
/**
* 生成缩略图
*
* @param oidPath 文件大小
* @param newPath 原文件路径
* @param smallSize 文件压缩倍数
* @return
*/
public static boolean imageGenerateSmall(String oidPath, String newPath, double smallSize) {
try {
File bigFile = new File(oidPath);
Image image = ImageIO.read(bigFile);
int width = image.getWidth(null);
int height = image.getHeight(null);
log.info(width+"x"+height);
int widthSmall = (int) (width / smallSize);
int heightSmall = (int) (height / smallSize);
log.info(widthSmall+"x"+heightSmall);
BufferedImage buffi = new BufferedImage(widthSmall, heightSmall, BufferedImage.TYPE_INT_RGB);
Graphics g = buffi.getGraphics();
g.drawImage(image, 0, 0, widthSmall, heightSmall, null);
g.dispose();
ImageIO.write(buffi, "jpg", new File(newPath));
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
/**
* 图片压缩,图片大小超过100K自动按比例压缩到100K以下
*
* @param fileSize 文件大小
* @param oidPath 原文件路径
* @param newPath 压缩后路径
* @return
* @throws Exception
*/
public static boolean imageCompress(long fileSize, String oidPath, String newPath) throws Exception {
boolean rs = true;
int kb = 400 * 1024;
if (fileSize > 100 * 1024) {
int smallSize = (int) (fileSize % kb == 0 ? fileSize / kb : fileSize / kb + 1);
double size = Math.ceil(Math.sqrt(smallSize));
log.info(String.valueOf(size));
rs = PicUtils.imageGenerateSmall(oidPath, newPath, size);
}
return rs;
}
public static void main(String[] args) throws Exception {
File file = new File("H:\\work\\yz\\img\\xx.jpg");
System.out.println("--------------文件大小(byte)----------------:"+file.length());
imageCompress(file.length(), "H:\\work\\yz\\img\\xx.jpg","H:\\work\\yz\\img\\xx"+ (new Random().nextInt(10000) + 1)+".jpg");
}
}
- THE END -
最后修改:2023年7月10日
非特殊说明,本博所有文章均为博主原创。
如若转载,请注明出处:https://www.95app.top/java%e5%8e%8b%e7%bc%a9%e5%9b%be%e7%89%87/