com.gitee.cliveyuan.tools.img.ImageTools Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of java-tools Show documentation
Show all versions of java-tools Show documentation
Some commonly used methods in java
package com.gitee.cliveyuan.tools.img;
import com.gitee.cliveyuan.tools.Assert;
import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.geometry.Positions;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
/**
* 图片工具
*
* doc
*
* @author clive
* Created on 2018/07/27
* @see net.coobird.thumbnailator.Thumbnails
* @since 1.0
*/
public class ImageTools {
private ImageTools() {
}
/**
* 压缩图片
*
* @param srcImg 原始图片
* @param scale 尺寸
* @param quality 压缩质量
* @param destImg 压缩后的图片
* @throws IOException
*/
public static void compress(String srcImg,
float scale,
float quality,
String destImg
) throws IOException {
Thumbnails.of(srcImg)
.scale(scale)
.outputQuality(quality)
.toFile(destImg);
}
/**
* 裁剪
*
* @param srcImg 原始图片
* @param x
* @param y
* @param width
* @param height
* @param destImg 裁剪后的图片
* @throws IOException
*/
public static void crop(
String srcImg,
int x, int y, int width, int height,
String destImg
) throws IOException {
Thumbnails.of(srcImg)
.sourceRegion(x, y, width, height)
.size(width, height)
.toFile(destImg);
}
/**
* 图片格式转换
*
* @param srcImg 原图片
* @param destImg 要转换的图片 (带格式)
*/
public static void convert(String srcImg, String destImg) {
Assert.notEmpty(srcImg, "src img is required");
Assert.notEmpty(destImg, "dest img is required");
ImageConvertTools.convert(srcImg, destImg);
}
/**
* 获取图片真实格式
*
* @param imgPath 图片路径
*/
public static String getRealType(String imgPath) {
return ImgTypeTools.getImgType(imgPath);
}
/**
* 添加水印图片
*
* @param targetImg 目标图片: 要添加水印的图片
* @param watermarkImg 水印图片
* @param positions 位置
* @param width 宽度
* @param height 高度
* @param opacity 透明度
* @param destImg 生成的图片
* @throws IOException
*/
public static void watermark(String targetImg,
String watermarkImg,
Positions positions,
int width,
int height,
float opacity,
String destImg
) throws IOException {
BufferedImage watermarkImage = ImageIO.read(new File(watermarkImg));
Thumbnails.of(targetImg)
.watermark(positions, watermarkImage, opacity)
.size(width, height)
.toFile(destImg);
}
}