1新建一个springboot项目 并且在pom里面 引入依赖 thumbnailator
<dependency>
<groupId>net.coobird</groupId>
<artifactId>thumbnailator</artifactId>
<version>0.4.8</version>
</dependency>
2 在test下面的目录下的测试类写
import net.coobird.thumbnailator.Thumbnailator;
import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.geometry.Position;
import net.coobird.thumbnailator.geometry.Positions;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import javax.imageio.ImageIO;
import java.awt.*;
import java.io.File;
import java.io.IOException;
@SpringBootTest
class PictestApplicationTests {
private String originFile="/Users/zhangxu/Desktop/origin.jpeg";
private String toFile = "/Users/zhangxu/Desktop/new.jpg";
private String waterImg="/Users/zhangxu/Desktop/可爱熊二.png";
/**
* 改变尺寸大小
* @throws IOException
*/
@Test
public void changeSizeTest() throws IOException {
Thumbnails.of(originFile).size(200,100).toFile(toFile);
}
/**
* 缩放
* @throws IOException
*/
@Test
public void scaleTest() throws IOException {
Thumbnails.of(originFile).scale(0.2).toFile(toFile);
}
/**
* 旋转
* @throws IOException
*/
@Test
public void rotateTest() throws IOException {
Thumbnails.of(originFile).scale(1).rotate(200).toFile(toFile);
}
/**
* 裁剪 居中裁剪 400*200
* @throws IOException
*/
@Test
public void regionTest() throws IOException {
Thumbnails.of(originFile).scale(1).sourceRegion(Positions.CENTER,400,200).toFile(toFile);
}
/**
* 加水印
*/
@Test
public void wasterMaskTest() throws IOException {
Thumbnails.of(originFile).scale(1).watermark(Positions.TOP_RIGHT, ImageIO.read(new File(waterImg)),0.6f).toFile(toFile);
}
}
上面的originFile为源文件 位置, toFile为保存后的位置, watermask为水印, 可以自己更改你自己的路径