網(wǎng)上有很多封裝好的包晚碾,我用的是這個(gè)库车,如下坐標(biāo)恤浪,項(xiàng)目地址
<!-- 圖片合成 -->
<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
搂妻,內(nèi)容如下:
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格式圖片轉(zhuǎn)MultipartFile對(duì)象
* @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格式圖片轉(zhuǎn)input輸入流
* @throws Exception
*/
public static InputStream base64ToInputStream(String base64Str) throws Exception {
byte[] bytes = base64ToByteArray(base64Str);
return new ByteArrayInputStream(bytes);
}
/**
* Base64格式圖片轉(zhuǎn)byte[]數(shù)組
* @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轉(zhuǎn)Base64格式
* @throws Exception
*/
public static String toBase64(InputStream in) throws Exception {
return toBase64(in,"jpg");
}
/**
* InputStream轉(zhuǎn)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目錄下打洼,必須/開(kāi)頭速址,如:/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("生活時(shí)光機(jī)");
params.setDesc("以時(shí)光為單位");
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);
}
}
這時(shí)直接調(diào)用就好了玩焰。如果需要轉(zhuǎn)換 MultipartFile對(duì)象
,可以如下調(diào)用
MultipartFile file = MerageImageUtil.base64ToMultipartFile("123.jpg", "123.jpg", "jpg", "Base64圖片字符串");
這樣就可以轉(zhuǎn)成 MultipartFile對(duì)象
了芍锚,注:123.jpg 是隨便給的昔园,只是給 Base64 圖片字符串一個(gè)源文件名稱,因?yàn)锽ase64圖片是沒(méi)名稱的并炮,后面獲取file原名稱就會(huì)null
默刚。