圖片處理工具(JAVA)
package com.michael.utils;
import lombok.extern.slf4j.Slf4j;
import javax.imageio.stream.FileImageInputStream;
import javax.imageio.stream.FileImageOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
@Slf4j
public class ImageUtils {
private static final Integer WIDTH = 300;
private static final Integer HEIGHT = 300;
private static final Float QUALITY = 0.9f;
public static String compression(String sourceFilePath, String newFilepath, int width, int height, float quality) {
try {
if (Strings.isEmpty(sourceFilePath))
return null;
File file = new File(sourceFilePath);
if (!file.exists()) {
log.warn("源文件不存在,請檢查");
throw new Exception("源文件不存在,請檢查");
}
if (Strings.isNotEmpty(newFilepath)) {
File f = new File(newFilepath);
if (!f.exists())
f.mkdirs();
}
Image srcFile = ImageIO.read(new File(sourceFilePath));
BufferedImage bImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
bImage.getGraphics().drawImage(srcFile, 0, 0, width, height, null);
String newFileAbsolutePath = newFilepath + "//" + Strings.uuid() + "_" + width + "×" + height + sourceFilePath.substring(sourceFilePath.lastIndexOf("."));
log.info("壓縮圖片路徑:{}", newFileAbsolutePath);
FileOutputStream out = new FileOutputStream(newFileAbsolutePath);
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
JPEGEncodeParam jep = JPEGCodec.getDefaultJPEGEncodeParam(bImage);
jep.setQuality(quality, true);
encoder.encode(bImage, jep);
out.close();
return newFileAbsolutePath;
} catch (FileNotFoundException e) {
log.error("圖片壓縮過程中出錯:{}", e.getMessage());
e.printStackTrace();
} catch (IOException e) {
log.error("圖片壓縮過程中出錯:{}", e.getMessage());
e.printStackTrace();
} catch (Exception e) {
log.error("圖片壓縮過程中出錯:{}", e.getMessage());
e.printStackTrace();
}
return "";
}
public static String compression(String sourceFilePath, String newFilepath) {
return compression(sourceFilePath, newFilepath, WIDTH, HEIGHT, QUALITY);
}
public static byte[] image2byte(String path) {
byte[] data = null;
FileImageInputStream input = null;
try {
input = new FileImageInputStream(new File(path));
ByteArrayOutputStream output = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int numBytesRead = 0;
while ((numBytesRead = input.read(buf)) != -1) {
output.write(buf, 0, numBytesRead);
}
data = output.toByteArray();
output.close();
input.close();
} catch (FileNotFoundException ex1) {
ex1.printStackTrace();
} catch (IOException ex1) {
ex1.printStackTrace();
}
return data;
}
public static void byte2image(byte[] data, String path) {
if (data.length < 3 || path.equals("")) return;
try {
FileImageOutputStream imageOutput = new FileImageOutputStream(new File(path));
imageOutput.write(data, 0, data.length);
imageOutput.close();
log.info("Make Picture success, Please find image in {}", path);
} catch (Exception ex) {
log.error("Exception: {}", ex);
ex.printStackTrace();
}
}
}