图片编辑工具类Thumbnails
1.导入依赖
<dependency>
<groupId>net.coobird</groupId>
<artifactId>thumbnailator</artifactId>
<version>0.4.8</version>
</dependency>
2.创建测试类
package com.atwu.miao.test;
import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.geometry.Positions;
import org.junit.Test;
import javax.imageio.ImageIO;
import java.io.File;
public class ThumbnailatorTest {
//定义读取和输出图片的路径
private String file = "D:\\desk\\temp\\img\\maotouying.jpg";
private String toFile = "D:\\desk\\temp\\img\\copy.png";
/**
* 修改长和宽
* @throws Exception
*/
@Test
public void test() throws Exception{
Thumbnails.of(file).size(1000,600).toFile(toFile);
}
/**
* 等比例缩放
* @throws Exception
*/
@Test
public void scale() throws Exception{
Thumbnails.of(file).scale(0.8).toFile(toFile);
}
/**
* 图片旋转
* @throws Exception
*/
@Test
public void rotate() throws Exception{
//rotate 之前必须调scale方法 不然会报错 java.lang.IllegalStateException: size is not set.
Thumbnails.of(file).scale(1).rotate(180).toFile(toFile);
}
/**
* 图片裁剪
* @throws Exception
*/
@Test
public void region() throws Exception{
//必须调scale方法
Thumbnails.of(file).scale(1).sourceRegion(Positions.CENTER,40,40).toFile(toFile);
}
public static final String watermark = "D:\\desk\\temp\\img\\haha.png";
/**
* 添加水印
* @throws Exception
*/
@Test
public void waterMark() throws Exception{
//必须调scale方法
Thumbnails.of(file).scale(1).watermark(Positions.BOTTOM_RIGHT, ImageIO.read(new File(watermark)),0.5f).toFile(toFile);
}
}
简洁到不行呢!