java 生成分享图片(二维码,图片拼接,文字编辑)生成分享图片(二维码,图片拼接,文字编辑)
需求背景需求背景
之前遇到过需要后端,根据每个用户生成带背景宣传图带二维码带用户图片带文字的合成图片的需求,自己当时花了半天的时间整理了
资料,今天把自己写的代码分享出来,如果有同样需求的人,希望能给个好评,有其他建议的童鞋,可以一起讨论交流。
文章下面贴有项目地址,感谢star
项目整合了二维码和日志,有需要的童鞋也可以做参考
图片缓冲类图片缓冲类 BufferedImage
BufferedImage类是Image的实现类,是可以把图片加载到内存的缓冲类,我写的代码中就基本上都是基于该类实现对图片的操作。
图片加载图片加载 Thumbnails
Thumbnails是谷歌开源的一套图片工具类
当我需要把本地图片加载进来得到BufferedImage对象的时候,我们可以通过
Thumbnails.of(filePath)
.scale(1)
.asBufferedImage();
如果是远程图片
Thumbnails.of(new URL(filePath))
.scale(1)
.asBufferedImage();
添加文本添加文本
/**
* 修改图片,返回修改后的图片缓冲区(只输出一行文本)
*/
public BufferedImage modifyImage(BufferedImage img, Object content, int x, int y) {
try {
int w = img.getWidth();
int h = img.getHeight();
g = img.createGraphics();
g.setBackground(Color.WHITE);
g.setColor(Color.BLACK);//设置字体颜色
if (this.font != null) {
g.setFont(this.font);
}
// 验证输出位置的纵坐标和横坐标
if (x >= h || y >= w) {
this.x = h - this.fontsize + 2;
this.y = w;
} else {
this.x = x;
this.y = y;
}
g.setFont( new Font("微软雅黑", Font.BOLD, 22));
if (content != null) {
g.drawString(content.toString(), this.x, this.y);
}
g.setBackground(Color.WHITE);
g.dispose();
} catch (Exception e) {
System.out.println(e.getMessage());
}
return img;
}
生成图片到本地生成图片到本地
ImageIO提供了write的方法,将图片文件打印到本地
/**
* 生成新图片到本地
*/
public boolean writeImageLocal(String newImage, BufferedImage img) {
boolean isok = false;
if (newImage != null && img != null) {
try {
File outputfile = new File(newImage);
isok = ImageIO.write(img, "jpg", outputfile);
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
return isok;
}
评论0