Java后台生成图片:
- 自定义图片内文字和图片位置。
- 可背景透明。
- 字体尺寸、颜色、间距等基本设置和透明度设置。
- 文本换行与居中。
- 加载外部字体。
原理
使用java图形化工具绘制图片。
注意:linux系统只支持ttf文件
代码实现
创建所需参数的实体类
import lombok.Data;
import java.awt.*;
import java.awt.image.BufferedImage;
/**
* 生成图片参数控制
*
* @author h
* @date Created in 2020/5/30 17:25
*/
@Data
public class ImageCreateEntity {
/**
* 宽度
*/
private Integer width = 100;
/**
* 高度
*/
private Integer height = 100;
/*==============图片内容==============*/
/**
* 图片内容
*/
private BufferedImage imgContent;
/**
* 图片宽度
*/
private int imgWidth = 100;
/**
* 图片宽度
*/
private int imgHeight = 100;
/**
* 图片渲染X起点
*/
private int imgX;
/**
* 图片渲染Y轴起点
*/
private int imgY;
/*=====================文本内容===================*/
/**
* 文本内容
*/
private String textContent;
/**
* 字体名称
*/
private String fontName = "";
/**
* 字体文件路径
*/
private String fontFilePath = "";
/**
* 字体尺寸
*/
private float fontSize = 20f;
/**
* 字体风格
*/
private int fontStyle = Font.PLAIN;
/**
* 字体颜色
*/
private Color fontColor = Color.BLACK;
/**
* 字体间距,默认值为零,与当前字体尺寸相关
*/
private Integer fontSpace = 0;
/**
* 行距
*/
private Integer linePadding = 10;
/**
* 文本透明度:值从0-1.0,依次变得不透明
*/
private float textTransparency = 1.0f;
/**
* 文本渲染X起点
*/
private Integer textX = 0;
/**
* 文本渲染Y轴起点
*/
private Integer textY = 0;
/**
* 左边距
*/
private Integer textLeftPadding = 0;
/**
* 右边距
*/
private Integer textRightPadding = 0;
/**
* 每行居中
*/
private boolean isCenterLine;
/*=================背景==============*/
/**
* 背景颜色
*/
private Color backgroundColor = Color.WHITE;
/**
* 背景是否透明
*/
private boolean isTransparentBackground = false;
/**
* 背景图片
*/
private BufferedImage backgroundImg;
}
复制代码
生成图片基本方法
创建一个 BufferedImage
,再通过Graphics2D
进行绘制,就可以得到一个简单的图片缓存。
Graphics2D class extends the Graphics class to provide more sophisticated control over geometry, coordinate transformations, color management,and text layout. This is the fundamental class for rendering 2-dimensional shapes, text and images on the Java(tm) platform.
Graphics2D类扩展了Graphics类,以提供对几何图形,坐标转换,颜色管理和文本布局的更复杂的控制。 这是在Java(tm)平台上渲染二维形状,文本和图像的基本类。
BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = bf.createGraphics();
//设置图片背景颜色
g2d.setBackground(Color.WHITE);
g2d.clearRect(0, 0, width, height);
//绘制图片内容
// 中间内容框画到背景图上
BufferedImage imgContent = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
//绘制图片
g2d.drawImage(imgContent.getSca