网上有很多封装好的包,我用的是这个,如下坐标,项目地址
<!-- 图片合成 -->
<dependency>
<groupId>com.freewayso</groupId>
<artifactId>image-combiner</artifactId>
<version>2.6.3</version>
</dependency>
或者
<dependency>
<groupId>io.github.chichengyu</groupId>
<artifactId>java-image-combiner</artifactId>
<version>1.1.0</version>
</dependency>
新建工具类MerageImageUtil.java
,内容如下:
package com.zyq.util;
import com.freewayso.image.combiner.ImageCombiner;
import com.freewayso.image.combiner.enums.Direction;
import com.freewayso.image.combiner.enums.OutputFormat;
import com.freewayso.image.combiner.enums.ZoomMode;
import lombok.Data;
import org.springframework.lang.Nullable;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;
import javax.imageio.ImageIO;
import java.awt.Color;
import java.awt.Font;
import java.awt.GraphicsEnvironment;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Objects;
/** 合并图片工具
* author xiaochi
* date 2024/9/2
*/
public class MerageImageUtil {
/**
* 显示所有可用字体
*/
public static void showFonts() throws InterruptedException {
GraphicsEnvironment e = GraphicsEnvironment.getLocalGraphicsEnvironment();
String[] fontName = e.getAvailableFontFamilyNames();
for (int i = 0; i < fontName.length; i++) {
System.out.println(fontName[i]);
}
}
/**
* Base64格式图片转MultipartFile对象
* @throws Exception
*/
public static MultipartFile base64ToMultipartFile(String fileName,String originalFilename,String contentType,String base64Str) throws Exception {
byte[] bytes = base64ToByteArray(base64Str);
return new DefaultMultiPartFile(fileName,originalFilename,contentType, bytes);
}
/**
* Base64格式图片转input输入流
* @throws Exception
*/
public static InputStream base64ToInputStream(String base64Str) throws Exception {
byte[] bytes = base64ToByteArray(base64Str);
return new ByteArrayInputStream(bytes);
}
/**
* Base64格式图片转byte[]数组
* @throws Exception
*/
public static byte[] base64ToByteArray(String base64Str) throws Exception {
base64Str = base64Str.replaceAll("data:image/(jpg|png|jpeg);base64,","");
return Base64.getDecoder().decode(base64Str);
}
/**
* InputStream转Base64格式
* @throws Exception
*/
public static String toBase64(InputStream in) throws Exception {
return toBase64(in,"jpg");
}
/**
* InputStream转Base64格式
* @throws Exception
*/
public static String toBase64(InputStream in,String imageType) throws Exception {
byte[] bytes = new byte[4096];
int len;
ByteArrayOutputStream out = new ByteArrayOutputStream();
while ((len = in.read(bytes)) != -1){
out.write(bytes,0,len);
}
return "data:image/"+imageType+";base64,"+ new String(Base64.getEncoder().encode(out.toByteArray()), StandardCharsets.UTF_8);
}
/**
* 合并图片与文字并输出Base64格式
* @throws Exception
*/
public static String toBase64(Params params) throws Exception {
InputStream in = merageImageAndTxt(params);
return toBase64(in,"jpg");
}
/**
* 合并图片与文字
* @throws Exception
*/
public static InputStream merageImageAndTxt(Params params) throws Exception {
//showFonts();
/*String bg = "https://img.thebeastshop.com/combine_image/funny_topic/resource/bg_3x4.png";
ImageCombiner combiner = new ImageCombiner(bg, OutputFormat.JPG);*/
int top = 1248;
ImageCombiner combiner = new ImageCombiner(ImageIO.read(new File(params.getBackImage())), OutputFormat.JPG);
BufferedImage cover = ImageIO.read(params.getCoverImage());
//叠加人物
combiner.addImageElement(cover, 0, 0,1248,top, ZoomMode.WidthHeight)
.setCenter(true)
.setRotate(0);
//Font font = new Font("Smiley Sans", Font.ITALIC, 150);//"微软雅黑"
String font = "微软雅黑";
if (!Objects.equals(params.getTitleFont(),null) && !Objects.equals(params.getTitleFont(),"")){
font = params.getTitleFont();
}
combiner.addTextElement(params.getTitle(), font,150, 150,100)
.setColor(Color.getHSBColor(223,212,184))
.setAutoBreakLine(0)
.setDirection(Direction.CenterLeftRight);
combiner.addTextElement(params.getDesc(),"楷体",48,250,850)
.setColor(Color.WHITE)
.setAutoBreakLine(0)
.setAlpha(.5F);
Font authorFont = new Font("黑体", Font.BOLD, 48);//"微软雅黑"
combiner.addTextElement(params.getAuthor(),authorFont,100,top+30)
.setColor(Color.BLACK)
.setSpace(.5F);
/*combiner.addImageElement("http://img.thebeastshop.com/images/index/imgs/8wzZ7St7KH.jpg", 10, 30)
.setCenter(true)
.setRotate(45);*/
combiner.combine();
if (Objects.equals(params.getSavePath(),null) || Objects.equals(params.getSavePath(),"")){
return combiner.getCombinedImageStream();
}
combiner.save(params.getSavePath());
return null;
}
@Data
public static class Params{
private String title;
private String desc;
private String author;
private String titleFont = "/font/SmileySans2.ttf";//如果是字体文件路径,放到resource的font目录下,必须/开头,如:/font/SmileySans2.ttf
private String savePath;
private String backImage;//背景图
//private String coverImage;//封面图
private InputStream coverImage;//封面图
}
public static class DefaultMultiPartFile implements MultipartFile {
private final String name;
private String originalFilename;
@Nullable
private String contentType;
private final byte[] content;
public DefaultMultiPartFile(String name, @Nullable byte[] content) {
this(name, name, (String)null, content);
}
public DefaultMultiPartFile(String name, String originalFilename, @Nullable String contentType, byte[] content) {
this.name = name;
this.originalFilename = originalFilename;
this.contentType = contentType;
this.content = content;
}
@Override
public String getName() {
return this.name;
}
@Override
public String getOriginalFilename() {
return this.originalFilename;
}
@Override
public String getContentType() {
return this.contentType;
}
@Override
public boolean isEmpty() {
return content.length==0;
}
@Override
public long getSize() {
return content.length;
}
@Override
public byte[] getBytes() throws IOException {
return content;
}
@Override
public InputStream getInputStream() throws IOException {
return new ByteArrayInputStream(content);
}
@Override
public void transferTo(File file) throws IOException, IllegalStateException {
FileCopyUtils.copy(this.content, file);
}
}
public static void main(String[] args) throws Exception {
Params params = new Params();
params.setTitle("生活时光机");
params.setDesc("以时光为单位");
params.setAuthor("汪新元.回忆录111");
params.setTitleFont("/font/SmileySans2.ttf");// params.setTitleFont("微软雅黑");
params.setSavePath("D:\\workspace\\demo2\\test.jpg");
params.setBackImage("D:\\image_test\\bg.jpg");
params.setCoverImage(new FileInputStream(new File("D:\\image_test\\people.jpg")));
merageImageAndTxt(params);
}
}
这时直接调用就好了。如果需要转换 MultipartFile对象
,可以如下调用
MultipartFile file = MerageImageUtil.base64ToMultipartFile("123.jpg", "123.jpg", "jpg", "Base64图片字符串");
这样就可以转成 MultipartFile对象
了,注:123.jpg 是随便给的,只是给 Base64 图片字符串一个源文件名称,因为Base64图片是没名称的,后面获取file原名称就会null
。