package com.ots.project.tool.exam;
|
import lombok.extern.slf4j.Slf4j;
|
import net.coobird.thumbnailator.Thumbnails;
|
import javax.imageio.ImageIO;
|
import java.awt.image.BufferedImage;
|
import java.io.File;
|
import java.io.FileInputStream;
|
import java.io.FileOutputStream;
|
import java.io.IOException;
|
import java.math.BigDecimal;
|
@Slf4j
|
public class PicUtils {
|
public static void main(String[] args) {
|
boolean flag = PicUtils.commpressPicForScale("/Users/shawnli/Downloads/1.jpg",
|
"/Users/shawnli/Downloads/2.jpg", 20, 0.5);
|
}
|
|
public static boolean commpressPicForScale(String srcPath, String desPath,
|
long desFileSize, double accuracy) {
|
if ("".equals(srcPath.trim()) || "".equals(srcPath.trim())) {
|
return false;
|
}
|
try {
|
File srcFile = new File(srcPath);
|
if (!srcFile.exists()) {
|
return false;
|
}
|
|
long srcFileSizeJPG = srcFile.length();
|
|
if (srcFileSizeJPG <= desFileSize * 1024) {
|
byte[] b = new byte[1024];
|
int a = 0;
|
|
File desFile = new File(desPath);
|
FileInputStream fis = new FileInputStream(srcFile);
|
FileOutputStream fos = new FileOutputStream(desFile);
|
while ((a = fis.read(b)) != -1) {
|
fos.write(b, 0, a);
|
}
|
return true;
|
}
|
|
Thumbnails.of(srcPath).scale(1f).toFile(desPath);
|
|
commpressPicCycle(desPath, desFileSize, accuracy);
|
} catch (Exception e) {
|
log.error("失败的文件" + srcPath);
|
log.error(e.getMessage());
|
return false;
|
}
|
return true;
|
}
|
private static void commpressPicCycle(String desPath, long desFileSize,
|
double accuracy) throws IOException {
|
File srcFileJPG = new File(desPath);
|
long srcFileSizeJPG = srcFileJPG.length();
|
|
if (srcFileSizeJPG <= desFileSize * 1024) {
|
return;
|
}
|
|
BufferedImage bim = ImageIO.read(srcFileJPG);
|
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();
|
Thumbnails.of(desPath).size(desWidth, desHeight)
|
.outputQuality(accuracy).toFile(desPath);
|
commpressPicCycle(desPath, desFileSize, accuracy);
|
}
|
|
public static boolean commpressPicForScale(String fileOriginalPath, String filePath) {
|
File fileSrcDir = new File(fileOriginalPath);
|
File fileDesDir = new File(filePath);
|
|
if (!fileSrcDir.isDirectory() || !fileDesDir.isDirectory()) {
|
return false;
|
}
|
for (File file : fileSrcDir.listFiles()) {
|
commpressPicForScale(file.getPath(),
|
filePath + file.getName(), 5, 0.5);
|
}
|
return true;
|
}
|
}
|