前言
日常开发中我们经常会遇到一些图片处理需求,比如图片太大了,我们需要将其大小压缩,或者是想裁剪图片的某个区域。在此分享一个比较是在的图片处理工具Thumbnails,下面也简单介绍几个常用的场景,还有更多的方法大家可以具体看看里面的实现
引入依赖
<dependencies>
<dependency>
<groupId>net.coobird</groupId>
<artifactId>thumbnailator</artifactId>
<version>0.4.13</version>
</dependency>
</dependencies>
功能介绍
一、等比压缩
/**
* 等比压缩
* @param inputFile 输入文件
* @param outputFile 输出文件
* @param maxDimension 需要压缩到的一个长度,比如(300*150 要压缩成150*75,则传150)
* @throws IOException
*/
public static void resizeImage(File inputFile, File outputFile, int maxDimension) throws IOException {
// 读取原始图像
BufferedImage inputImage = ImageIO.read(inputFile);
// 计算缩放比例
double scaleFactor = (double)maxDimension / Math.max(inputImage.getWidth(), inputImage.getHeight());
// 计算新的宽度和高度
int scaledWidth = (int)(inputImage.getWidth() * scaleFactor);
int scaledHeight = (int)(inputImage.getHeight() * scaleFactor);
Thumbnails.of(inputFile).size(scaledWidth,scaledHeight).toFile(outputFile);
}
二、添加水印
/**
*
* @param inputFile 输入文件
* @param outputFile 输出文件
* @param positions 水印位置
* @param watermarkFile 水印图片
* @param transparency 水印透明度 0.5f
* @throws IOException
*/
public static void watermark(File inputFile,
File outputFile,
Positions positions,
File watermarkFile,
float transparency) {
try {
//水印位置、水印图片、透明度
Thumbnails.of(inputFile)
.watermark(positions, ImageIO.read(watermarkFile), transparency)
.toFile(outputFile);
}catch (Exception e){
e.printStackTrace();
}
}
三、旋转图片
/**
* 旋转图片
*
* @param inputFile 输入文件
* @param outputFile 输出文件
* @param angle 旋转角度
* @throws IOException
*/
public static void rotate(File inputFile,
File outputFile,
int angle) {
try {
Thumbnails.of(inputFile)
.rotate(angle)
.toFile(outputFile);
} catch (Exception e) {
e.printStackTrace();
}
}
四、指定区域裁剪图片
/**
* 表示某区域向左和向上裁剪X和Y的像素区域,生成w*h像素的输出文件
* @param inputFile
* @param outputFile
* @param positions
* @param X
* @param Y
* @param w
* @param h
*/
private void positionCroppingImg(File inputFile,
File outputFile,
Positions positions,
int X,
int Y,
int w,
int h) {
try {
Thumbnails.of(inputFile)
.sourceRegion(positions, X, Y)
.size(w, h)
.keepAspectRatio(false).toFile(outputFile);
} catch (Exception e) {
e.printStackTrace();
}
}
五、自定义区域裁剪
/**
* 自定义区域裁剪
* @param inputFile
* @param outputFile
* @param X1
* @param Y1
* @param X2
* @param Y2
* @param w
* @param h
*/
private void divCroppingImg(File inputFile,
File outputFile,
int X1,
int Y1,
int X2,
int Y2,
int w,
int h) {
try {
Thumbnails.of(inputFile)
.sourceRegion(X1, Y1, X2, Y2)
.size(w, h)
.keepAspectRatio(false).toFile(outputFile);
} catch (Exception e) {
e.printStackTrace();
}
}