ImageUtils.java
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.*;
import lombok.extern.slf4j.Slf4j;
import sun.font.FontDesignMetrics;
/**
* 图片工具类
* @author deyin.mdy
* @date 2020/11/12
*/
@Slf4j
public class ImageUtils {
/**
* 默认文本位置-x
*/
private static final Integer DEFAULT_X = 10;
/**
* 默认文本位置-y
*/
private static final Integer DEFAULT_Y = 10;
/**
* 默认文本字体
*/
private static final String DEFAULT_FONT_NAME = "楷体";
/**
* 默认文本大小
*/
private static final Integer DEFAULT_FONT_SIZE = 15;
/**
* 默认文本字体
*/
private static final Font DEFAULT_FONT = new Font(DEFAULT_FONT_NAME, Font.BOLD, DEFAULT_FONT_SIZE);
/**
* 默认画布背景颜色
*/
private static final Color DEFAULT_BACKGROUND_COLOR = Color.WHITE;
/**
* 默认文本颜色
*/
private static final Color DEFAULT_FONT_COLOR = Color.BLACK;
/**
* 将图片流写成图片文件
*
* @param bufImg
* @param formatName 图片格式,可以是png,jpg
* @param filePath 图片地址
* @return 图片文件
* @throws IOException
*/
public static File writeImageFile(BufferedImage bufImg, String formatName, String filePath) throws IOException {
File imageFile = new File(filePath);
ImageIO.write(bufImg, formatName, imageFile);
return imageFile;
}
/**
* 创建一个文字画布
*
* @param line 指定文字
* @param width 画布宽
* @param height 画布高
* @param font 文字的字体
* @param backgroundColor 画布背景色
* @param fontColor 文字颜色
* @param x 文字所在位置
* @param y 文字所在位置
* @return
*/
public static BufferedImage genStringBufferedImage(String line, Integer width, Integer height, Font font,
Color backgroundColor, Color fontColor, Integer x, Integer y) {
BufferedImage srcBi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D graphics = (Graphics2D)srcBi.getGraphics();
//设置背景色
graphics.setBackground(backgroundColor);
//背景色充满画布
graphics.clearRect(0, 0, width, height);
// 抗锯齿
graphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
//设置字体颜色
graphics.setColor(fontColor);
graphics.setFont(font);
FontDesignMetrics metrics = FontDesignMetrics.getMetrics(font);
//画字符串,x坐标即字符串左边位置,y坐标是指baseline的y坐标,即字体所在矩形的左上角y坐标+ascent
//基线对齐改为顶边对齐
graphics.drawString(line, x, y + metrics.getAscent());
return srcBi;
}
/**
* 创建文字默认画布
*
* @param line 指定文字
* @param width 画布宽
* @param height 画布高
* @return
*/
public static BufferedImage genStringDefaultBufferedImage(String line, Integer width, Integer height) {
return genStringBufferedImage(line, width, height, DEFAULT_FONT, DEFAULT_BACKGROUND_COLOR, DEFAULT_FONT_COLOR, DEFAULT_X, DEFAULT_Y);
}
/**
* 创建一个居中文字画布
*
* @param centerWords 指定文字
* @param width 画布宽
* @param height 画布高
* @param font 文字的字体
* @param backgroundColor 画布背景色
* @param fontColor 文字颜色
* @return
*/
public static BufferedImage genStringCenterBufferedImage(String centerWords, Integer width, Integer height,
Font font,
Color backgroundColor, Color fontColor) {
BufferedImage srcBi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
int owidth = srcBi.getWidth();
int oheight = srcBi.getHeight();
Graphics2D graphics = (Graphics2D)srcBi.getGraphics();
//设置背景色
graphics.setBackground(backgroundColor);
//背景色充满画布
graphics.clearRect(0, 0, width, height);
// 抗锯齿
graphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
//设置字体颜色
graphics.setColor(fontColor);
graphics.setFont(font);
FontDesignMetrics metrics = FontDesignMetrics.getMetrics(font);
int strWidth = metrics.stringWidth(centerWords);
int strHeight = metrics.getHeight();
//左边位置
int left = (owidth - strWidth) / 2;
//顶边位置+上升距离(原本字体基线位置对准画布的y坐标导致字体偏上ascent距离,加上ascent后下移刚好顶边吻合)
int top = (oheight - strHeight) / 2 + metrics.getAscent();
graphics.drawString(centerWords, left, top);
return srcBi;
}
/**
* @param bufImg 源图片
* @description 转化成透明背景的图片
*/
public static BufferedImage transferAlpha(BufferedImage bufImg) {
try {
Image image = bufImg;
ImageIcon imageIcon = new ImageIcon(image);
BufferedImage bufferedImage = new BufferedImage(imageIcon.getIconWidth(), imageIcon.getIconHeight(),
BufferedImage.TYPE_4BYTE_ABGR);
Graphics2D g2D = (Graphics2D)bufferedImage.getGraphics();
g2D.drawImage(imageIcon.getImage(), 0, 0, imageIcon.getImageObserver());
int alpha = 0;
for (int j1 = bufferedImage.getMinY(); j1 < bufferedImage.getHeight(); j1++) {
for (int j2 = bufferedImage.getMinX(); j2 < bufferedImage.getWidth(); j2++) {
int rgb = bufferedImage.getRGB(j2, j1);
int R = (rgb & 0xff0000) >> 16;
int G = (rgb & 0xff00) >> 8;
int B = (rgb & 0xff);
if (((255 - R) < 30) && ((255 - G) < 30) && ((255 - B) < 30)) {
rgb = ((alpha + 1) << 24) | (rgb & 0x00ffffff);
}
bufferedImage.setRGB(j2, j1, rgb);
}
}
g2D.drawImage(bufferedImage, 0, 0, imageIcon.getImageObserver());
// 直接输出文件用来测试结果
// ImageIO.write(bufferedImage, "png", new File("/Users/deyin.mdy/Downloads/test5.png"));
return bufferedImage;
} catch (Exception e) {
e.printStackTrace();
} finally {
}
return null;
}
}
POIThumbnailatorUtils.java
/**
*
*/
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import javax.imageio.ImageIO;
import lombok.extern.slf4j.Slf4j;
import net.coobird.thumbnailator.Thumbnails;
/**
* @author deyin.mdy
*
*/
@Slf4j
public class POIThumbnailatorUtils {
/**
*
* @param orgPicturePath-原始图
* @param appendPicturePath-追加的图片
* @param x
* -追加图片的X轴
* @param y
* -追加图片的Y轴
* @param offsetX
* - 偏移量 - 宽度
* @param offsetY
* - 偏移量-高度
* @param targetPath
* - 输出文件地址
*/
public static boolean mergePictures(String orgPicturePath, String appendPicturePath, Integer x, Integer y,
Integer offsetX, Integer offsetY, String targetPath) {
try {
log.debug("orgPicturePath={},addPicturePath={},targetPath={}", orgPicturePath, appendPicturePath,
targetPath);
log.debug("x={},y={},offsetX={},offsetY={}", x, y, offsetX, offsetY);
File appendPicture = new File(appendPicturePath);
BufferedImage appendImg = ImageIO.read(new FileInputStream(appendPicture));
// 源图宽度
int orgWidth = appendImg.getWidth();
// 源图高度
int orghight = appendImg.getHeight();
int swidth = orgWidth / 2 + offsetX;
int shight = orghight + offsetY;
int targetX = x - swidth;
int targetY = y - shight;
if (targetX < 0) {
targetX = 0;
}
if (targetY < 0) {
targetY = 0;
}
Thumbnails.of(orgPicturePath).scale(1f).// 图片缩放100%, 不能和size()一起使用
watermark(new MyPosition(targetX, targetY), appendImg, 0.9f). // 在指定位置添加水印,几乎不透明
toFile(targetPath);
return true;
} catch (IOException e) {
log.error(e.getMessage(), e);
return false;
}
}
/**
* 调整图片的大小
*
* @param orgPicturePath
* -- 原图地址
* @param targetPath
* -- 新图地址
* @param scale--放大比例
* @return
*/
public static void reScale(String orgPicturePath, String targetPath, double scale) {
try {
Thumbnails.of(orgPicturePath).scale(scale).// 图片缩放80%, 不能和size()一起使用
toFile(targetPath);
} catch (IOException e) {
log.error(e.getMessage(), e);
}
}
/**
* 图片合并
* @param orgPicturePath 原始图片
* @param appendImg 追加的图片流
* @param x 追加的图片流x轴
* @param y 追加的图片流x轴
* @param offsetX - 偏移量 - 宽度
* @param offsetY - 偏移量-高度
* @param targetPath
* @return
*/
public static boolean mergePictures(String orgPicturePath, BufferedImage appendImg, Integer x, Integer y,
Integer offsetX, Integer offsetY, String targetPath) {
try {
log.debug("mergePictures with BufferedImage orgPicturePath={},targetPath={}", orgPicturePath, targetPath);
log.debug("x={},y={},offsetX={},offsetY={}", x, y, offsetX, offsetY);
// 源图宽度
int orgWidth = appendImg.getWidth();
// 源图高度
int orghight = appendImg.getHeight();
int swidth = orgWidth / 2 + offsetX;
int shight = orghight + offsetY;
int targetX = x - swidth;
int targetY = y - shight;
if (targetX < 0) {
targetX = 0;
}
if (targetY < 0) {
targetY = 0;
}
Thumbnails.of(orgPicturePath).scale(1f).// 图片缩放100%, 不能和size()一起使用
watermark(new MyPosition(targetX, targetY), appendImg, 0.9f). // 在指定位置添加水印,几乎不透明
toFile(targetPath);
return true;
} catch (IOException e) {
log.error(e.getMessage(), e);
return false;
}
}
}
ImageTest.java
import java.awt.image.BufferedImage;
/**
* @author deyin.mdy
* @date 2020/11/12
*/
public class ImageTest {
public static void main(String[] args) {
try {
BufferedImage bufferedImage = ImageUtils.genStringDefaultBufferedImage("爆Seed", 1024, 768);
ImageUtils.writeImageFile(bufferedImage, "png", "/Users/deyin.mdy/Downloads/new1.png");
bufferedImage = ImageUtils.transferAlpha(bufferedImage);
ImageUtils.writeImageFile(bufferedImage, "png", "/Users/deyin.mdy/Downloads/new2.png");
String orgPicturePath = "/Users/deyin.mdy/Downloads/PosterTemplate.png";
int x = 650;
int y = 1100;
int offsetX = 20;
int offsetY = 20;
String targetPath = "/Users/deyin.mdy/Downloads/new3.png";
POIThumbnailatorUtils.mergePictures(orgPicturePath, bufferedImage, x, y, offsetX, offsetY, targetPath);
System.out.println("done.");
} catch (Exception e) {
e.printStackTrace();
}
}
}