Commit 590c4e4e by ws

海报创建

1 parent 038e1f91
Showing 24 changed files with 1529 additions and 3 deletions
package com.linkwechat.web.controller.wecom;
import com.linkwechat.common.core.controller.BaseController;
import com.linkwechat.common.core.domain.AjaxResult;
import com.linkwechat.common.utils.SnowFlakeUtil;
import com.linkwechat.wecom.domain.WePoster;
import com.linkwechat.wecom.domain.WePosterFont;
import com.linkwechat.wecom.domain.WePosterSubassembly;
import com.linkwechat.wecom.service.IWePosterFontService;
import com.linkwechat.wecom.service.IWePosterService;
import com.linkwechat.wecom.service.IWePosterSubassemblyService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
@RestController
@RequestMapping(value = "wecom/poster/")
public class WePosterController extends BaseController {
@Resource
private IWePosterService wePosterService;
@Resource
private IWePosterSubassemblyService wePosterSubassemblyService;
@Resource
private IWePosterFontService wePosterFontService;
@PostMapping(value = "insert")
@Transactional(rollbackFor = RuntimeException.class)
public AjaxResult insert(@RequestBody WePoster poster){
wePosterService.generateSimpleImg(poster);
poster.setId(SnowFlakeUtil.nextId());
poster.setDelFlag(1);
wePosterService.saveOrUpdate(poster);
poster.getPosterSubassemblyList().forEach(wePosterSubassembly -> {
wePosterSubassembly.setDelFlag(1);
wePosterSubassembly.setId(SnowFlakeUtil.nextId());
wePosterSubassembly.setPosterId(poster.getId());
});
wePosterSubassemblyService.saveBatch(poster.getPosterSubassemblyList());
return AjaxResult.success("创建成功");
}
@PutMapping(value = "update")
public AjaxResult update(@RequestBody WePoster poster){
if(poster.getId() == null){
return AjaxResult.error("id为空");
}
wePosterService.generateSimpleImg(poster);
wePosterService.saveOrUpdate(poster);
List<WePosterSubassembly> posterSubassemblyList = wePosterSubassemblyService.lambdaQuery().eq(WePosterSubassembly::getPosterId,poster.getId()).eq(WePosterSubassembly::getDelFlag,1).list();
Map<Long,WePosterSubassembly> posterSubassemblyMap = posterSubassemblyList.stream().collect(Collectors.toMap(WePosterSubassembly::getId,p->p));
List<WePosterSubassembly> insertList = new ArrayList<>();
List<WePosterSubassembly> updateList = new ArrayList<>();
poster.getPosterSubassemblyList().forEach(wePosterSubassembly -> {
if(wePosterSubassembly.getId() == null){
wePosterSubassembly.setId(SnowFlakeUtil.nextId());
wePosterSubassembly.setPosterId(poster.getId());
wePosterSubassembly.setDelFlag(1);
insertList.add(wePosterSubassembly);
}else {
posterSubassemblyMap.remove(wePosterSubassembly.getId());
updateList.add(wePosterSubassembly);
}
});
if(!CollectionUtils.isEmpty(insertList)) {
wePosterSubassemblyService.saveBatch(insertList);
}
if(!CollectionUtils.isEmpty(updateList)) {
wePosterSubassemblyService.updateBatchById(updateList);
}
List<WePosterSubassembly> deleteList = new ArrayList<>(posterSubassemblyMap.values());
if(!CollectionUtils.isEmpty(deleteList)){
deleteList.forEach(wePosterSubassembly -> wePosterSubassembly.setDelFlag(0));
wePosterSubassemblyService.updateBatchById(deleteList);
}
return AjaxResult.success("修改成功");
}
@GetMapping(value = "list")
public AjaxResult list(){
List<WePoster> fontList = wePosterService.lambdaQuery()
.eq(WePoster::getDelFlag,1)
.orderByDesc(WePoster::getCreateTime)
.list();
return AjaxResult.success(fontList);
}
@GetMapping(value = "entity/{id}")
public AjaxResult entity(@PathVariable Long id){
return AjaxResult.success(wePosterService.selectOne(id));
}
@GetMapping(value = "page")
public AjaxResult page(){
startPage();
List<WePoster> fontList = wePosterService.lambdaQuery()
.eq(WePoster::getDelFlag,1)
.orderByDesc(WePoster::getCreateTime)
.list();
return AjaxResult.success(getDataTable(fontList));
}
@DeleteMapping(value = "delete/{id}")
public AjaxResult deletePosterFont(@PathVariable Long id){
wePosterService.lambdaUpdate().set(WePoster::getDelFlag,0).eq(WePoster::getId,id);
wePosterSubassemblyService.lambdaUpdate().set(WePosterSubassembly::getDelFlag,0).eq(WePosterSubassembly::getPosterId,id).eq(WePosterSubassembly::getFontId,1);
return AjaxResult.success("删除成功");
}
}
package com.linkwechat.web.controller.wecom;
import com.linkwechat.common.core.controller.BaseController;
import com.linkwechat.common.core.domain.AjaxResult;
import com.linkwechat.common.utils.SnowFlakeUtil;
import com.linkwechat.web.controller.common.CommonController;
import com.linkwechat.wecom.domain.WePosterFont;
import com.linkwechat.wecom.service.IWePosterFontService;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;
@RestController
@RequestMapping(value = "wecom/posterFont/")
public class WePosterFontController extends BaseController {
@Resource
private IWePosterFontService wePosterFontService;
@PostMapping(value = "posterFont")
public AjaxResult insertPosterFont(@RequestBody WePosterFont posterFont){
posterFont.setId(SnowFlakeUtil.nextId());
posterFont.setDelFlag(1);
wePosterFontService.save(posterFont);
return AjaxResult.success("创建成功");
}
@PutMapping(value = "posterFont")
public AjaxResult updatePosterFont(@RequestBody WePosterFont posterFont){
if(posterFont.getId() == null){
return AjaxResult.error("id为空");
}
wePosterFontService.saveOrUpdate(posterFont);
return AjaxResult.success("修改成功");
}
@GetMapping(value = "posterFontList")
public AjaxResult selectPosterFontList(){
List<WePosterFont> fontList = wePosterFontService.lambdaQuery()
.eq(WePosterFont::getDelFlag,1)
.orderByDesc(WePosterFont::getOrder)
.orderByDesc(WePosterFont::getCreateTime)
.list();
return AjaxResult.success(fontList);
}
@GetMapping(value = "posterFontPage")
public AjaxResult selectPosterFontPage(){
startPage();
List<WePosterFont> fontList = wePosterFontService.lambdaQuery()
.eq(WePosterFont::getDelFlag,1)
.orderByDesc(WePosterFont::getOrder)
.orderByDesc(WePosterFont::getCreateTime)
.list();
return AjaxResult.success(getDataTable(fontList));
}
@DeleteMapping(value = "posterFont/{id}")
public AjaxResult deletePosterFont(@PathVariable Long id){
wePosterFontService.lambdaUpdate().set(WePosterFont::getDelFlag,0).eq(WePosterFont::getId,id);
return AjaxResult.success("删除成功");
}
}
......@@ -101,6 +101,16 @@
<artifactId>jjwt</artifactId>
</dependency>
<dependency>
<groupId>io.vertx</groupId>
<artifactId>vertx-core</artifactId>
</dependency>
<dependency>
<groupId>io.vertx</groupId>
<artifactId>vertx-web-client</artifactId>
</dependency>
<!-- redis 缓存操作 -->
<dependency>
<groupId>org.springframework.boot</groupId>
......@@ -137,6 +147,8 @@
</dependency>
<!--防止进入swagger页面报类型转换错误,排除2.9.2中的引用,手动增加1.5.21版本-->
<dependency>
<groupId>io.swagger</groupId>
......
......@@ -22,6 +22,7 @@ public class BaseEntity implements Serializable
private static final long serialVersionUID = 1L;
/** 搜索值 */
@TableField(exist = false)
private String searchValue;
/** 创建者 */
......@@ -39,17 +40,21 @@ public class BaseEntity implements Serializable
private Date updateTime=new Date();
/** 备注 */
@TableField(exist = false)
private String remark;
/** 开始时间 */
@JsonIgnore
@TableField(exist = false)
private String beginTime;
/** 结束时间 */
@JsonIgnore
@TableField(exist = false)
private String endTime;
/** 请求参数 */
@TableField(exist = false)
private Map<String, Object> params;
public String getSearchValue()
......
package com.linkwechat.common.enums;
/**
* 海报组件类型
* @author ws
*/
public enum WePosterSubassemblyType {
/**
* 自定义文本
*/
plainText(0,"自定义文本"),
/**
* 图片
*/
picture(1,"图片"),
/**
* 二维码
*/
QRCode(2,"二维码");
private Integer code;
private String label;
private WePosterSubassemblyType(Integer code,String label){
this.code = code;
this.label = label;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
}
package com.linkwechat.common.utils.img;
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class ImageUtils {
private final static JLabel J_LABEL = new JLabel();
public static void main(String[] args) throws Exception{
/*File file = WsFileUtils.createFile("D:\\网页\\-1.jpg");
try {
BufferedImage bufferedImage = ImageIO.read(file);
BufferedImage newBufferedImage = copyBufferedImage(bufferedImage,BufferedImage.TYPE_INT_RGB);
Graphics2D graphics2D = newBufferedImage.createGraphics();
System.out.println("图片宽度"+newBufferedImage.getWidth());
System.out.println("图片长度"+newBufferedImage.getHeight());
//Font font = new Font("微软雅黑",Font.PLAIN,96);
//Font font1 = new Font("宋体",Font.PLAIN,120);
Color color = getColor("#7FFF00");
Stream.iterate(0,i->i+1).limit(100).forEach(j->{
Font font = null;
try {
font = Font.createFont(Font.TRUETYPE_FONT, WsFileUtils.createFile("D:\\网页\\SourceHanSansCN-Normal.ttf"));
} catch (FontFormatException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
font = font.deriveFont(Font.PLAIN,96);
System.out.println(font.getSize());
String context = "u易语言突然人fgsd豆腐干豆腐干地方合同已经同意就过分";
long startTime = System.currentTimeMillis();
FontMetrics fontMetrics = J_LABEL.getFontMetrics(font);
fontMetrics = J_LABEL.getFontMetrics(font);
List<LineText> list = splitContext(context,fontMetrics,50,0,bufferedImage.getWidth()-100,bufferedImage.getHeight(),3);
long endTime = System.currentTimeMillis();
System.out.println("拆解成行:" + (endTime - startTime));
startTime = System.currentTimeMillis();
for(int i = 0; i < list.size(); i++) {
LineText lineText = list.get(i);
writeFontBufferedImage(newBufferedImage, lineText.getText(), lineText.getPointX(), lineText.getPointY(), font, color);
BufferedImage image = enlargementBufferedImage(bufferedImage,0.2,BufferedImage.TYPE_3BYTE_BGR);
mergeBufferedImage(newBufferedImage,image,200,500);
}
endTime = System.currentTimeMillis();
System.out.println(endTime - startTime);
try {
ImageIO.write(newBufferedImage,"jpg",WsFileUtils.createFile("D:\\网页\\"+j+".jpg"));
} catch (IOException e) {
e.printStackTrace();
}
});
} catch (IOException e) {
e.printStackTrace();
}*/
}
public static byte[] changeImageSize(InputStream inputStream, Integer size) {
try {
BufferedImage oldBufferedImage = ImageIO.read(inputStream);
int oldWidth = oldBufferedImage.getWidth();
int oldHeight = oldBufferedImage.getHeight();
int newWidth = 0;
int newHeight = 0;
if (size >= 0) {
newWidth = oldWidth * size;
newHeight = oldHeight * size;
} else {
size = -size;
newWidth = oldWidth / size;
newHeight = oldHeight / size;
}
BufferedImage newBufferedImage = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);
Graphics2D newGraphics2D = newBufferedImage.createGraphics();
newGraphics2D.setBackground(Color.WHITE);
newGraphics2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
newGraphics2D.drawImage(oldBufferedImage, 0, 0, newWidth, newHeight, null);
oldBufferedImage.flush();
OutputStream outputStream = new ByteArrayOutputStream();
ImageIO.write(newBufferedImage, "jpg", outputStream);
newBufferedImage.flush();
byte[] bytes = ((ByteArrayOutputStream) outputStream).toByteArray();
outputStream.flush();
outputStream.close();
return bytes;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 切割图片
*
* @param inputStream
* @param x
* @param y
* @param width
* @param height
* @return
*/
public static byte[] cropImage(InputStream inputStream, int x, int y, int width, int height) {
BufferedImage bufferedImage = null;
byte bytes[] = null;
try {
bufferedImage = ImageIO.read(inputStream);
bytes = cropImage(bufferedImage, x, y, width, height);
} catch (Exception e) {
e.printStackTrace();
} finally {
bufferedImage.flush();
try {
inputStream.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
inputStream = null;
}
}
return bytes;
}
public static byte[] cropImage(BufferedImage bufferedImage, int x, int y, int width, int height) {
//BufferedImage newBufferedImage = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
BufferedImage copyBufferedImage = bufferedImage.getSubimage(x, y, width, height);
/*Graphics2D graphics2D = newBufferedImage.createGraphics();
graphics2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
graphics2D.drawImage(copyBufferedImage,0,0,width,height,null);
copyBufferedImage.flush();*/
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte[] bytes = null;
try {
ImageIO.write(copyBufferedImage, "jpg", outputStream);
bytes = outputStream.toByteArray();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
outputStream.flush();
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
outputStream = null;
}
//newBufferedImage.flush();
}
return bytes;
}
public static void inciseImage(InputStream inputStream, Integer direction, Integer directionValue, String fileName, String path) {
try {
BufferedImage bufferedImage = ImageIO.read(inputStream);
int width = bufferedImage.getWidth();
int height = bufferedImage.getHeight();
if (direction == 1) {
int directionNum = height / directionValue;
if (directionNum == 0) {
return;
}
int i = 0;
for (i = 0; i < directionNum; i++) {
byte bytes[] = cropImage(bufferedImage, 0, i * directionValue, width, directionValue);
byteToFile(bytes, fileName + "-" + i, "jpg", path);
}
int directionSurplus = height % directionValue;
if (directionSurplus > 0) {
byte bytes[] = cropImage(bufferedImage, 0, height - directionSurplus, width, directionSurplus);
byteToFile(bytes, fileName + "-" + (i + 1), "jpg", path);
}
} else if (direction == 2) {
int directionNum = width / directionValue;
if (directionNum == 0) {
return;
}
int i = 0;
for (; i < directionNum; i++) {
byte bytes[] = cropImage(bufferedImage, i * directionValue, 0, directionValue, height);
byteToFile(bytes, fileName + "-" + i, "jpg", path);
}
int directionSurplus = width % directionValue;
if (directionSurplus > 0) {
byte bytes[] = cropImage(bufferedImage, height - directionSurplus, 0, directionSurplus, height);
byteToFile(bytes, fileName + "-" + (i + 1), "jpg", path);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static BufferedImage filePathToBufferedImage(String filePath) throws Exception {
File file = new File(filePath);
if (!file.isFile()) {
throw new FileNotFoundException("文件路径为目录");
}
if (!file.exists()) {
throw new FileNotFoundException("文件不存在");
}
BufferedImage bufferedImage = ImageIO.read(file);
return bufferedImage;
}
/**
* 复制
*
* @param bufferedImage
* @param bufferedImageType
* @return
*/
public static BufferedImage copyBufferedImage(BufferedImage bufferedImage, Integer bufferedImageType) {
BufferedImage newBufferedImage = new BufferedImage(bufferedImage.getWidth(), bufferedImage.getHeight(), bufferedImageType);
Graphics2D graphics2D = newBufferedImage.createGraphics();
graphics2D.drawImage(bufferedImage, null, 0, 0);
return newBufferedImage;
}
/**
* 放大缩小
*
* @param bufferedImage
* @param enlargementTimes
* @return
*/
public static BufferedImage enlargementBufferedImage(BufferedImage bufferedImage, double enlargementTimes, Integer bufferedImageType) {
int newWidth = (int) (bufferedImage.getWidth() * enlargementTimes);
int newHeight = (int) (bufferedImage.getHeight() * enlargementTimes);
BufferedImage newBufferedImage = new BufferedImage(newWidth, newHeight, bufferedImageType);
Graphics2D graphics2D = newBufferedImage.createGraphics();
graphics2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
graphics2D.drawImage(bufferedImage, 0, 0, newWidth, newHeight, null);
return newBufferedImage;
}
/**
* 将图片改为固定尺寸
*
* @param bufferedImage
* @param bufferedImageType
* @param width
* @param height
* @return
*/
public static BufferedImage fixedDimensionBufferedImage(BufferedImage bufferedImage, Integer bufferedImageType, Integer width, Integer height) {
BufferedImage newBufferedImage = new BufferedImage(width, height, bufferedImageType);
Graphics2D graphics2D = newBufferedImage.createGraphics();
graphics2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
graphics2D.drawImage(bufferedImage, 0, 0, width, height, null);
return newBufferedImage;
}
/**
* 合并两个图层
*
* @param backBufferedImage
* @param frontBufferedImage
* @param pointX
* @param pointY
* @return
*/
public static BufferedImage mergeBufferedImage(BufferedImage backBufferedImage, BufferedImage frontBufferedImage, Integer pointX, Integer pointY) {
Graphics2D graphics2D = backBufferedImage.createGraphics();
graphics2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
graphics2D.drawImage(frontBufferedImage, pointX, pointY, frontBufferedImage.getWidth(), frontBufferedImage.getHeight(), null);
return backBufferedImage;
}
/**
* 在图层上写字
*
* @param bufferedImage
* @param str
* @param pointX
* @param pointY
* @param font
* @param color
* @return
*/
public static BufferedImage writeFontBufferedImage(BufferedImage bufferedImage, String str, Integer pointX, Integer pointY, Font font, Color color) {
Graphics2D graphics2D = bufferedImage.createGraphics();
/*graphics2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
graphics2D.setColor(color);
graphics2D.setFont(font);
graphics2D.drawString(str, pointX, pointY);*/
writeFontBufferedImage(graphics2D,str,pointX,pointY,font,color);
return bufferedImage;
}
public static void writeFontBufferedImage(Graphics2D graphics2D, String str, Integer pointX, Integer pointY, Font font, Color color) {
graphics2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
graphics2D.setColor(color);
graphics2D.setFont(font);
graphics2D.drawString(str, pointX, pointY);
}
/**
* byte数组转成文件
*
* @param bytes
* @param fileName
* @param fileType
* @param filePath
*/
public static void byteToFile(byte bytes[], String fileName, String fileType, String filePath) {
File fileFloder = new File(filePath);
if (!fileFloder.exists()) {
fileFloder.mkdirs();
}
fileFloder = null;
///fileName = WsStringUtils.stringTrim(fileName);
filePath = filePath + fileName + "." + fileType;
File file = new File(filePath);
FileOutputStream fileOutputStream = null;
FileChannel fileChannel = null;
try {
if (!file.exists()) {
file.createNewFile();
}
fileOutputStream = new FileOutputStream(file);
fileChannel = fileOutputStream.getChannel();
ByteBuffer byteBuffer = ByteBuffer.wrap(bytes);
fileChannel.write(byteBuffer);
byteBuffer.clear();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (fileChannel != null) {
fileChannel.close();
}
if (fileOutputStream != null) {
fileOutputStream.flush();
fileOutputStream.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static BufferedImage createMosaic(BufferedImage bufferedImage, Integer pointX, Integer pointY, Integer width, Integer height, Integer level) {
Integer bufferImageWidth = bufferedImage.getWidth();
Integer bufferImageHeight = bufferedImage.getHeight();
Integer x = pointX;
Integer y = pointY;
Integer chunkWidth = width / level;
Integer chunkHeight = height / level;
chunkWidth = chunkWidth == 0 ? 1 : chunkWidth;
chunkHeight = chunkHeight == 0 ? 1 : chunkHeight;
x -= chunkWidth;
y -= chunkHeight;
Random random = new Random();
Graphics2D graphics2D = bufferedImage.createGraphics();
/*Rectangle rectangle = new Rectangle();
rectangle.setRect(pointX,pointY,chunkWidth,chunkHeight);*/
while (x < pointX + width) {
x += chunkWidth;
while (y < pointY + height) {
y += chunkHeight;
Integer randomX = random.nextInt(chunkWidth);
Integer randomY = random.nextInt(chunkWidth);
Integer modificationX = 0;
Integer modificationY = 0;
if (x + randomX >= bufferImageWidth) {
modificationX = (x + randomX) - bufferImageWidth + 1;
}
if (y + randomY >= bufferImageHeight) {
modificationY = (y + randomY) - bufferImageHeight + 1;
}
System.out.println("(" + (x + randomX - modificationX) + "," + (y + randomY - modificationY) + ")(" + x + "," + y + ")");
int rgb = bufferedImage.getRGB(x + randomX - modificationX, y + randomY - modificationY);
int a = rgb >>> 24;
int r = (rgb << 8) >>> 24;
int g = (rgb << 16) >>> 24;
int b = (rgb << 24) >>> 24;
//System.out.println("a:"+a+" r:"+r+" g:"+g+" b:"+b);
Color color = new Color(r, g, b);
graphics2D.setColor(color);
graphics2D.fillRect(x, y, chunkWidth, chunkHeight);
}
y = pointY - chunkHeight;
}
return bufferedImage;
}
/**
* bufferedImage转成byte数组
*
* @param bufferedImage
* @param type
* @return
*/
public static byte[] bufferedImageToByteArray(BufferedImage bufferedImage, String type) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
byte[] bytes = null;
try {
ImageIO.write(bufferedImage, type, byteArrayOutputStream);
bytes = byteArrayOutputStream.toByteArray();
bufferedImage.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
byteArrayOutputStream.flush();
byteArrayOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return bytes;
}
/**
* 把字符串拆成行
* @param context
* @param fontMetrics
* @param width
* @param height
* @param type 1 右对齐 2 居中 3 左对齐
* @return
*/
public static List<LineText> splitContext(String context,FontMetrics fontMetrics,int pointX,int pointY,int width,int height,Integer type){
context = new String(context.getBytes(StandardCharsets.UTF_8));
Font font = fontMetrics.getFont();
char[] chars = context.toCharArray();
List<LineText> returnLineList = new ArrayList<>();
StringBuilder sb = new StringBuilder();
int size = 0;
int nowHeight = font.getSize();
int charSize = 0;
for(char c:chars){
charSize = fontMetrics.charWidth(c);
size += charSize;
if(size >= width){
returnLineList.add(new LineText(pointX,width,pointY + nowHeight,sb.toString(),size - charSize,type));
sb = new StringBuilder();
sb.append(c);
nowHeight += font.getSize();
size = charSize;
}else {
sb.append(c);
}
if(nowHeight > height){
sb = new StringBuilder();
break;
}
}
if(sb.length() > 0){
returnLineList.add(new LineText(pointX,width,pointY + nowHeight,sb.toString(),size,type));
}
return returnLineList;
}
public static Color getColor(String value){
if(!value.startsWith("#")){
throw new RuntimeException("格式错误");
}
return new Color(Integer.parseInt(value.substring(1,3),16),Integer.parseInt(value.substring(3,5),16),Integer.parseInt(value.substring(5,7),16));
}
public static FontMetrics getFontMetrics(Font font){
return J_LABEL.getFontMetrics(font);
}
public static class LineText{
private final Integer pointX;
private final Integer pointY;
private final String text;
private final Integer length;
public LineText(Integer pointX,Integer width,Integer height,String text,Integer length,Integer type){
this.text = text;
this.length = length;
this.pointY = height;
if(type.equals(1)){
this.pointX = pointX;
}else if(type.equals(2)){
this.pointX = (pointX+width - length)/2;
}else if(type.equals(3)){
this.pointX = pointX+width - length;
}else {
throw new RuntimeException("不支持的类型");
}
}
public String getText() {
return text;
}
public Integer getLength() {
return length;
}
public Integer getPointX() {
return pointX;
}
public Integer getPointY() {
return pointY;
}
}
}
package com.linkwechat.common.utils.img;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.vertx.core.Vertx;
import io.vertx.core.buffer.Buffer;
import io.vertx.ext.web.client.WebClient;
import java.awt.*;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
/**
* @author ws
*/
public class NetFileUtils {
private static final Vertx vertx = Vertx.vertx();
private static final WebClient webClient = WebClient.create(vertx);
public static void main(String[] args) {
FileCallable fileCallable = getNetFile("https://pc-index-skin.cdn.bcebos.com/hiphoto/51631423522.jpg?x-bce-process=image/crop,x_0,y_13,w_1999,h_1250");
getByteArrayOutputStream(fileCallable,true);
}
public static FileCallable getNetFile(String urlPath){
FileCallable fileCallable = new FileCallable();
webClient.getAbs(urlPath).send().onSuccess(response -> {
if(response.statusCode() == 200 || response.statusCode() == 302){
Buffer buffer = response.body();
buffer.getByteBuf();
byte[] bytes = buffer.getBytes();
fileCallable.setFile(bytes);
}else {
fileCallable.error();
}
}).onFailure(throwable -> {
fileCallable.error();
throwable.printStackTrace();
});
return fileCallable;
}
public static ByteArrayOutputStream getByteArrayOutputStream(FileCallable fileCallable,boolean clearBuf){
try {
ByteBuf byteBuf = fileCallable.call();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
int byteLength = 1024;
byte[] bytes = new byte[byteLength];
int length = 0;
while ((length = byteBuf.readableBytes()) > 0){
byteBuf.readBytes(bytes, 0, Math.min(length, byteLength));
byteArrayOutputStream.write(bytes,0, Math.min(length, byteLength));
}
if(!clearBuf){
byteBuf.resetReaderIndex();
}else {
byteBuf.clear();
}
return byteArrayOutputStream;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static class FileCallable implements Callable<ByteBuf>{
private final CountDownLatch countDownLatch = new CountDownLatch(1);
private volatile ByteBuf byteBuf;
/**
* Computes a result, or throws an exception if unable to do so.
*
* @return computed result
* @throws Exception if unable to compute a result
*/
@Override
public ByteBuf call() throws Exception {
boolean k = countDownLatch.await(10,TimeUnit.MINUTES);
if(k && byteBuf != null){
return byteBuf;
}else {
throw new RuntimeException("获取失败");
}
}
public void setFile(byte[] bytes){
ByteBuf byteBuf = Unpooled.directBuffer();
byteBuf.writeBytes(bytes);
this.byteBuf = byteBuf;
countDownLatch.countDown();
}
public void error(){
countDownLatch.countDown();
}
}
}
......@@ -75,6 +75,15 @@
<artifactId>linkwe-wecom</artifactId>
</dependency>
<dependency>
<groupId>io.vertx</groupId>
<artifactId>vertx-core</artifactId>
</dependency>
<dependency>
<groupId>io.vertx</groupId>
<artifactId>vertx-web-client</artifactId>
</dependency>
</dependencies>
......
package com.linkwechat.wecom.domain;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.linkwechat.common.core.domain.BaseEntity;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.util.ArrayList;
import java.util.List;
/**
* 海报
* @author ws
*/
@EqualsAndHashCode(callSuper = true)
@Data
@TableName(value = "we_poster")
public class WePoster extends BaseEntity {
@TableId
private Long id;
/**
* 海报标题
*/
@TableField
private String title;
/**
* 背景图片
*/
@TableField
private String backgroundImgPath;
/**
* 示例图片
*/
@TableField
private String sampleImgPath;
/**
* 海报类型 1 通用海报
*/
@TableField
private Long type;
@TableField
private Integer delFlag;
@TableField
private Integer width;
@TableField
private Integer height;
/**
* 海报组件数组
*/
@TableField(exist = false)
private List<WePosterSubassembly> posterSubassemblyList;
public static void main(String[] args) {
WePoster wePoster = new WePoster();
wePoster.setDelFlag(1);
wePoster.setTitle("你好世界");
wePoster.setHeight(1000);
wePoster.setWidth(1000);
wePoster.setType(1L);
wePoster.setBackgroundImgPath("1");
wePoster.setPosterSubassemblyList(new ArrayList<>());
for(int i = 0; i < 1; i++){
WePosterSubassembly subassembly = new WePosterSubassembly();
subassembly.setFontColor("#544875");
subassembly.setFontId(1L);
subassembly.setHeight(100);
subassembly.setWidth(100);
subassembly.setDelFlag(1);
subassembly.setLeft(1);
subassembly.setTop(1);
subassembly.setFontTextAlign(1);
wePoster.getPosterSubassemblyList().add(subassembly);
}
System.out.println(JSON.toJSONString(wePoster));
}
}
package com.linkwechat.wecom.domain;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.linkwechat.common.core.domain.BaseEntity;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
* 海报字体实体
* @author ws
*/
@EqualsAndHashCode(callSuper = true)
@Data
@TableName(value = "we_poster_font")
public class WePosterFont extends BaseEntity {
/**
* id
*/
@TableId
private Long id;
/**
* 字体名称
*/
@TableField(value = "font_name")
private String fontName;
/**
* 字体网络地址
*/
@TableField(value = "font_url")
private String fontUrl;
/**
* 字体排序
*/
@TableField(value = "`order`")
private Integer order;
/**
* 状态
*/
@TableField(value = "del_flag")
private Integer delFlag;
}
package com.linkwechat.wecom.domain;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.linkwechat.common.core.domain.BaseEntity;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
* 海报组成部件
* @author ws
*/
@EqualsAndHashCode(callSuper = true)
@Data
@TableName(value = "we_poster_subassembly")
public class WePosterSubassembly extends BaseEntity {
@TableId
private Long id;
@TableField
private Long posterId;
/**
* x坐标
*/
@TableField(value = "`left`")
private Integer left;
/**
* y坐标
*/
@TableField
private Integer top;
/**
* 宽度
*/
@TableField
private Integer width;
/**
* 高度
*/
@TableField
private Integer height;
/**
* 类型 1 固定文本 2 固定图片 3 二维码图片
*/
@TableField
private Integer type;
@TableField
private Long fontId;
/**
* 字体大小(像素大小)
*/
@TableField
private Integer fontSize;
/**
* 字体颜色(十六进制)
*/
@TableField
private String fontColor;
/**
* 字体对齐方式 0 左对齐 1居中 2右对齐
*/
@TableField
private Integer fontTextAlign;
/**
* 图片网络地址
*/
@TableField
private String imgPath;
@TableField
private Integer delFlag;
/**
* 文字内容
*/
@TableField
private String content;
/**
* 字体实体
*/
@TableField(exist = false)
private WePosterFont font;
}
package com.linkwechat.wecom.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.linkwechat.wecom.domain.WePosterFont;
/**
* 海报字体
* @author ws
*/
public interface WePosterFontMapper extends BaseMapper<WePosterFont> {
}
package com.linkwechat.wecom.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.linkwechat.wecom.domain.WePoster;
import com.linkwechat.wecom.domain.WePosterFont;
/**
* 海报
* @author ws
*/
public interface WePosterMapper extends BaseMapper<WePoster> {
}
package com.linkwechat.wecom.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.linkwechat.wecom.domain.WePosterFont;
import com.linkwechat.wecom.domain.WePosterSubassembly;
/**
* 海报组件
* @author ws
*/
public interface WePosterSubassemblyMapper extends BaseMapper<WePosterSubassembly>{
}
package com.linkwechat.wecom.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.linkwechat.wecom.domain.WePosterFont;
import java.awt.*;
/**
* 海报
* @author ws
*/
public interface IWePosterFontService extends IService<WePosterFont> {
/**
* 获取字体
* @param id
* @param size
* @return
*/
public Font getFont(Long id,Integer size);
}
package com.linkwechat.wecom.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.linkwechat.wecom.domain.WePoster;
/**
* 海报
* @author ws
*/
public interface IWePosterService extends IService<WePoster> {
/**
* 查询一条
* @param id
* @return
*/
public WePoster selectOne(Long id);
/**
* 生成海报图片地址
* @param poster
* @return
*/
public String generateSimpleImg(WePoster poster);
}
package com.linkwechat.wecom.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.linkwechat.wecom.domain.WePosterSubassembly;
import java.util.List;
/**
* 海报
* @author ws
*/
public interface IWePosterSubassemblyService extends IService<WePosterSubassembly> {
}
package com.linkwechat.wecom.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.linkwechat.common.utils.img.NetFileUtils;
import com.linkwechat.wecom.domain.WePosterFont;
import com.linkwechat.wecom.mapper.WePosterFontMapper;
import com.linkwechat.wecom.service.IWePosterFontService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.awt.*;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* 海报字体
* @author ws
*/
@Service
public class WePosterFontServiceImpl extends ServiceImpl<WePosterFontMapper,WePosterFont> implements IWePosterFontService {
@Resource
private WePosterFontMapper wePosterFontMapper;
/**
* 字体数据缓存
*/
private final Map<Long, Font> FONT_MAP = new ConcurrentHashMap<>();
/**
* 获取字体
*
* @param id
* @param size
* @return
*/
@Override
public Font getFont(Long id, Integer size) {
WePosterFont posterFont = this.getById(id);
if(posterFont == null){
throw new RuntimeException("字体id为:"+id+"的字体不存在");
}
Font font;
if((font=FONT_MAP.get(posterFont.getId())) != null){
return font.deriveFont((float)size);
}
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(NetFileUtils.getByteArrayOutputStream(NetFileUtils.getNetFile(posterFont.getFontUrl()),false).toByteArray());
try {
font = Font.createFont(Font.TRUETYPE_FONT, byteArrayInputStream);
FONT_MAP.put(posterFont.getId(),font);
font = font.deriveFont((float)size);
return font;
} catch (FontFormatException e) {
e.printStackTrace();
throw new RuntimeException("字体格式错误");
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
package com.linkwechat.wecom.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.linkwechat.common.utils.file.FileUploadUtils;
import com.linkwechat.common.utils.file.FileUtils;
import com.linkwechat.common.utils.img.ImageUtils;
import com.linkwechat.common.utils.img.NetFileUtils;
import com.linkwechat.wecom.domain.WePoster;
import com.linkwechat.wecom.domain.WePosterFont;
import com.linkwechat.wecom.domain.WePosterSubassembly;
import com.linkwechat.wecom.mapper.WePosterMapper;
import com.linkwechat.wecom.service.IWePosterFontService;
import com.linkwechat.wecom.service.IWePosterService;
import com.linkwechat.wecom.service.IWePosterSubassemblyService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.NetworkInterface;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* 海报字体
*
* @author ws
*/
@Service
public class WePosterServiceImpl extends ServiceImpl<WePosterMapper, WePoster> implements IWePosterService {
@Resource
private WePosterMapper wePosterMapper;
@Resource
private IWePosterSubassemblyService posterSubassemblyService;
@Resource
private IWePosterFontService posterFontService;
/**
* 查询一条
*
* @param id
* @return
*/
@Override
public WePoster selectOne(Long id) {
WePoster poster = this.lambdaQuery()
.eq(WePoster::getId, id)
.eq(WePoster::getDelFlag, 1)
.getEntity();
if (poster == null) {
return null;
}
poster.setPosterSubassemblyList(posterSubassemblyService.lambdaQuery().eq(WePosterSubassembly::getPosterId, poster.getId()).list());
if (!CollectionUtils.isEmpty(poster.getPosterSubassemblyList())) {
List<Long> fontIdList = poster.getPosterSubassemblyList().stream().filter(wePosterSubassembly -> wePosterSubassembly.getFontId() != null).map(WePosterSubassembly::getFontId).distinct().collect(Collectors.toList());
if (!CollectionUtils.isEmpty(fontIdList)) {
List<WePosterFont> fontList = posterFontService.lambdaQuery().in(WePosterFont::getId, fontIdList).list();
if (!CollectionUtils.isEmpty(fontList)) {
Map<Long, WePosterFont> fontMap = fontList.stream().collect(Collectors.toMap(WePosterFont::getId, f -> f));
poster.getPosterSubassemblyList().stream().filter(wePosterSubassembly -> wePosterSubassembly.getFontId() != null).forEach(wePosterSubassembly -> {
WePosterFont font = fontMap.get(wePosterSubassembly.getFontId());
if (font != null) {
wePosterSubassembly.setFont(font);
}
});
}
}
}
return poster;
}
/**
* 生成海报图片地址
*
* @param poster
* @return
*/
@Override
public String generateSimpleImg(WePoster poster) {
Map<Long, Font> fontMap = poster.getPosterSubassemblyList().stream().filter(wePosterSubassembly -> wePosterSubassembly.getFontId() != null)
.collect(Collectors.toMap(WePosterSubassembly::getFontId, wePosterSubassembly -> posterFontService.getFont(wePosterSubassembly.getFontId(), wePosterSubassembly.getFontSize())));
Map<String, NetFileUtils.FileCallable> fileCallableMap = poster.getPosterSubassemblyList().stream().filter(wePosterSubassembly -> StringUtils.isNotBlank(wePosterSubassembly.getImgPath())).distinct().collect(Collectors.toMap(WePosterSubassembly::getImgPath, wePosterSubassembly -> {
return NetFileUtils.getNetFile(wePosterSubassembly.getImgPath());
}));
if (CollectionUtils.isEmpty(fileCallableMap)) {
fileCallableMap = new HashMap<>();
}
fileCallableMap.put(poster.getBackgroundImgPath(), NetFileUtils.getNetFile(poster.getBackgroundImgPath()));
Map<String, BufferedImage> bufferedImageMap = fileCallableMap.entrySet().stream().collect(Collectors.toMap(stringFileCallableEntry -> stringFileCallableEntry.getKey(), stringFileCallableEntry -> {
try {
return ImageIO.read(new ByteArrayInputStream(NetFileUtils.getByteArrayOutputStream(stringFileCallableEntry.getValue(), false).toByteArray()));
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException("图片读取错误");
}
}));
BufferedImage backgroundImg = bufferedImageMap.get(poster.getBackgroundImgPath());
poster.getPosterSubassemblyList().forEach(wePosterSubassembly -> {
if (wePosterSubassembly.getFontId() != null) {
Font font = fontMap.get(wePosterSubassembly.getFontId());
FontMetrics fontMetrics = ImageUtils.getFontMetrics(font);
Color color;
if (StringUtils.isNotBlank(wePosterSubassembly.getFontColor())) {
color = ImageUtils.getColor(wePosterSubassembly.getFontColor());
} else {
color = Color.BLACK;
}
List<ImageUtils.LineText> lineTextList = ImageUtils.splitContext(wePosterSubassembly.getContent(), fontMetrics, wePosterSubassembly.getLeft(), wePosterSubassembly.getTop(), wePosterSubassembly.getWidth(), wePosterSubassembly.getHeight(), wePosterSubassembly.getFontTextAlign());
lineTextList.forEach(lineText -> {
ImageUtils.writeFontBufferedImage(backgroundImg, lineText.getText(), lineText.getPointX(), lineText.getPointY(), font, color);
});
} else {
BufferedImage bufferedImage = bufferedImageMap.get(wePosterSubassembly.getImgPath());
bufferedImage = ImageUtils.fixedDimensionBufferedImage(bufferedImage, BufferedImage.TYPE_INT_RGB, wePosterSubassembly.getWidth(), wePosterSubassembly.getHeight());
ImageUtils.mergeBufferedImage(backgroundImg, bufferedImage, wePosterSubassembly.getLeft(), wePosterSubassembly.getTop());
}
});
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
try {
ImageIO.write(backgroundImg, "jpg", byteArrayOutputStream);
ImageUtils.byteToFile(byteArrayOutputStream.toByteArray(),"测试"+System.currentTimeMillis(),"jpg","D:/网页/");
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException("图片生成错误");
}
return null;
}
}
package com.linkwechat.wecom.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.linkwechat.wecom.domain.WePosterSubassembly;
import com.linkwechat.wecom.mapper.WePosterSubassemblyMapper;
import com.linkwechat.wecom.service.IWePosterSubassemblyService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
/**
* 海报字体
* @author ws
*/
@Service
public class WePosterSubassemblyServiceImpl extends ServiceImpl<WePosterSubassemblyMapper, WePosterSubassembly> implements IWePosterSubassemblyService {
@Resource
private WePosterSubassemblyMapper wePosterSubassemblyMapper;
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.linkwechat.wecom.mapper.WePosterFontMapper">
</mapper>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.linkwechat.wecom.mapper.WePosterMapper">
</mapper>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.linkwechat.wecom.mapper.WePosterSubassemblyMapper">
</mapper>
\ No newline at end of file
......@@ -37,12 +37,22 @@
<hutool.version>5.4.1</hutool.version>
<zxing.version>3.3.3</zxing.version>
<mybatis-plus.version>3.4.0</mybatis-plus.version>
<vertx.version>4.0.0</vertx.version>
<netty-version>4.1.49.Final</netty-version>
</properties>
<!-- 依赖声明 -->
<dependencyManagement>
<dependencies>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-bom</artifactId>
<version>${netty-version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<!-- SpringBoot的依赖配置-->
<dependency>
<groupId>org.springframework.boot</groupId>
......@@ -235,8 +245,17 @@
<version>${mybatis-plus.version}</version>
</dependency>
<dependency>
<groupId>io.vertx</groupId>
<artifactId>vertx-core</artifactId>
<version>${vertx.version}</version>
</dependency>
<dependency>
<groupId>io.vertx</groupId>
<artifactId>vertx-web-client</artifactId>
<version>${vertx.version}</version>
</dependency>
</dependencies>
</dependencyManagement>
......@@ -292,7 +311,7 @@
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>false</enabled>
<enabled>true</enabled>
</snapshots>
</pluginRepository>
</pluginRepositories>
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!