Commit e16cf9ec by 星梦苍天

海报修改

1 parent f823303c
......@@ -5,19 +5,24 @@ import com.linkwechat.common.core.controller.BaseController;
import com.linkwechat.common.core.domain.AjaxResult;
import com.linkwechat.common.core.page.TableDataInfo;
import com.linkwechat.common.enums.BusinessType;
import com.linkwechat.common.enums.MediaType;
import com.linkwechat.wecom.domain.WeMaterial;
import com.linkwechat.wecom.domain.dto.ResetCategoryDto;
import com.linkwechat.wecom.domain.dto.WeMediaDto;
import com.linkwechat.wecom.domain.vo.WeMaterialFileVO;
import com.linkwechat.wecom.service.IWeMaterialService;
import com.linkwechat.wecom.service.IWePosterService;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;
/**
* 企业微信素材Controller
......@@ -33,6 +38,9 @@ public class WeMaterialController extends BaseController {
@Autowired
private IWeMaterialService materialService;
@Resource
private IWePosterService wePosterService;
/**
* 查询素材列表
*/
......@@ -41,7 +49,19 @@ public class WeMaterialController extends BaseController {
public TableDataInfo list(@RequestParam(value = "categoryId", required = false) String categoryId
, @RequestParam(value = "search", required = false) String search,@RequestParam(value = "mediaType") String mediaType) {
startPage();
List<WeMaterial> list = materialService.findWeMaterials(categoryId, search,mediaType);
List<WeMaterial> list;
if(StringUtils.isNotBlank(mediaType) && mediaType.equals(MediaType.POSTER.getType())){
list = wePosterService.list(Long.valueOf(categoryId),search).stream().map(wePoster -> {
WeMaterial weMaterial = new WeMaterial();
weMaterial.setMaterialName(wePoster.getTitle());
weMaterial.setMaterialUrl(wePoster.getSampleImgPath());
weMaterial.setId(wePoster.getId());
return weMaterial;
}).collect(Collectors.toList());
}else {
list = materialService.findWeMaterials(categoryId, search,mediaType);
}
return getDataTable(list);
}
......
......@@ -2,7 +2,10 @@ package com.linkwechat.web.controller.wecom;
import com.linkwechat.common.core.controller.BaseController;
import com.linkwechat.common.core.domain.AjaxResult;
import com.linkwechat.common.enums.MediaType;
import com.linkwechat.common.utils.SnowFlakeUtil;
import com.linkwechat.common.utils.StringUtils;
import com.linkwechat.wecom.domain.WeMaterial;
import com.linkwechat.wecom.domain.WePoster;
import com.linkwechat.wecom.domain.WePosterFont;
import com.linkwechat.wecom.domain.WePosterSubassembly;
......@@ -17,11 +20,15 @@ import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import java.awt.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* @author ws
*/
@RestController
@RequestMapping(value = "wecom/poster/")
@Api(description = "海报")
......@@ -43,10 +50,14 @@ public class WePosterController extends BaseController {
public AjaxResult insert(@RequestBody WePoster poster){
wePosterService.generateSimpleImg(poster);
poster.setId(SnowFlakeUtil.nextId());
poster.setDelFlag(1);
poster.setDelFlag(0);
poster.setMediaType(MediaType.POSTER.getType());
/*if(poster.getCategoryId() == null){
return AjaxResult.error("请选择海报分类");
}*/
wePosterService.saveOrUpdate(poster);
poster.getPosterSubassemblyList().forEach(wePosterSubassembly -> {
wePosterSubassembly.setDelFlag(1);
wePosterSubassembly.setDelFlag(0);
wePosterSubassembly.setId(SnowFlakeUtil.nextId());
wePosterSubassembly.setPosterId(poster.getId());
});
......@@ -62,6 +73,7 @@ public class WePosterController extends BaseController {
if(poster.getId() == null){
return AjaxResult.error("id为空");
}
poster.setMediaType(null);
wePosterService.generateSimpleImg(poster);
wePosterService.saveOrUpdate(poster);
List<WePosterSubassembly> posterSubassemblyList = wePosterSubassemblyService.lambdaQuery().eq(WePosterSubassembly::getPosterId,poster.getId()).eq(WePosterSubassembly::getDelFlag,1).list();
......@@ -72,7 +84,7 @@ public class WePosterController extends BaseController {
if(wePosterSubassembly.getId() == null){
wePosterSubassembly.setId(SnowFlakeUtil.nextId());
wePosterSubassembly.setPosterId(poster.getId());
wePosterSubassembly.setDelFlag(1);
wePosterSubassembly.setDelFlag(0);
insertList.add(wePosterSubassembly);
}else {
posterSubassemblyMap.remove(wePosterSubassembly.getId());
......@@ -87,21 +99,23 @@ public class WePosterController extends BaseController {
}
List<WePosterSubassembly> deleteList = new ArrayList<>(posterSubassemblyMap.values());
if(!CollectionUtils.isEmpty(deleteList)){
deleteList.forEach(wePosterSubassembly -> wePosterSubassembly.setDelFlag(0));
deleteList.forEach(wePosterSubassembly -> wePosterSubassembly.setDelFlag(1));
wePosterSubassemblyService.updateBatchById(deleteList);
}
return AjaxResult.success("修改成功");
}
@GetMapping(value = "list")
/*@GetMapping(value = "list")
@ApiOperation("列表查询海报")
public AjaxResult list(){
public AjaxResult list(Long categoryId,String name){
List<WePoster> fontList = wePosterService.lambdaQuery()
.eq(WePoster::getDelFlag,1)
.eq(WePoster::getDelFlag,0)
.eq(categoryId != null,WePoster::getCategoryId,categoryId)
.like(StringUtils.isNotBlank(name),WePoster::getTitle,name)
.orderByDesc(WePoster::getCreateTime)
.list();
return AjaxResult.success(fontList);
}
}*/
@GetMapping(value = "entity/{id}")
@ApiOperation("查询海报详情")
......@@ -111,10 +125,12 @@ public class WePosterController extends BaseController {
@GetMapping(value = "page")
@ApiOperation("分页查询海报")
public AjaxResult page(){
public AjaxResult page(Long categoryId,String name){
startPage();
List<WePoster> fontList = wePosterService.lambdaQuery()
.eq(WePoster::getDelFlag,1)
.eq(WePoster::getDelFlag,0)
.eq(categoryId != null,WePoster::getCategoryId,categoryId)
.like(StringUtils.isNotBlank(name),WePoster::getTitle,name)
.orderByDesc(WePoster::getCreateTime)
.list();
return AjaxResult.success(getDataTable(fontList));
......@@ -124,11 +140,12 @@ public class WePosterController extends BaseController {
@ApiOperation(value = "删除海报")
@Transactional(rollbackFor = RuntimeException.class)
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);
wePosterService.lambdaUpdate().set(WePoster::getDelFlag,1).eq(WePoster::getId,id);
wePosterSubassemblyService.lambdaUpdate().set(WePosterSubassembly::getDelFlag,1).eq(WePosterSubassembly::getPosterId,id);
return AjaxResult.success("删除成功");
}
}
......@@ -2,6 +2,7 @@ package com.linkwechat.web.controller.wecom;
import com.linkwechat.common.core.controller.BaseController;
import com.linkwechat.common.core.domain.AjaxResult;
import com.linkwechat.common.enums.MediaType;
import com.linkwechat.common.utils.SnowFlakeUtil;
import com.linkwechat.web.controller.common.CommonController;
import com.linkwechat.wecom.domain.WePosterFont;
......@@ -14,6 +15,9 @@ import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;
/**
* @author ws
*/
@RestController
@RequestMapping(value = "wecom/posterFont/")
@Api(description = "海报字体")
......@@ -28,7 +32,8 @@ public class WePosterFontController extends BaseController {
@Transactional(rollbackFor = RuntimeException.class)
public AjaxResult insertPosterFont(@RequestBody WePosterFont posterFont){
posterFont.setId(SnowFlakeUtil.nextId());
posterFont.setDelFlag(1);
posterFont.setDelFlag(0);
posterFont.setMediaType(MediaType.POSTER_FONT.getType());
wePosterFontService.save(posterFont);
return AjaxResult.success("创建成功");
}
......@@ -41,6 +46,7 @@ public class WePosterFontController extends BaseController {
if(posterFont.getId() == null){
return AjaxResult.error("id为空");
}
posterFont.setMediaType(null);
wePosterFontService.saveOrUpdate(posterFont);
return AjaxResult.success("修改成功");
}
......@@ -49,7 +55,7 @@ public class WePosterFontController extends BaseController {
@ApiOperation("列表查询海报字体")
public AjaxResult selectPosterFontList(){
List<WePosterFont> fontList = wePosterFontService.lambdaQuery()
.eq(WePosterFont::getDelFlag,1)
.eq(WePosterFont::getDelFlag,0)
.orderByDesc(WePosterFont::getOrder)
.orderByDesc(WePosterFont::getCreateTime)
.list();
......@@ -61,7 +67,7 @@ public class WePosterFontController extends BaseController {
public AjaxResult selectPosterFontPage(){
startPage();
List<WePosterFont> fontList = wePosterFontService.lambdaQuery()
.eq(WePosterFont::getDelFlag,1)
.eq(WePosterFont::getDelFlag,0)
.orderByDesc(WePosterFont::getOrder)
.orderByDesc(WePosterFont::getCreateTime)
.list();
......@@ -72,7 +78,7 @@ public class WePosterFontController extends BaseController {
@ApiOperation("删除海报字体")
@Transactional(rollbackFor = RuntimeException.class)
public AjaxResult deletePosterFont(@PathVariable Long id){
wePosterFontService.lambdaUpdate().set(WePosterFont::getDelFlag,0).eq(WePosterFont::getId,id);
wePosterFontService.lambdaUpdate().set(WePosterFont::getDelFlag,1).eq(WePosterFont::getId,id);
return AjaxResult.success("删除成功");
}
......
......@@ -14,7 +14,15 @@ public enum MediaType {
IMAGE("0", "image"),
VOICE("1", "voice"),
VIDEO("2", "video"),
FILE("3", "file");
FILE("3", "file"),
/**
* 海报
*/
POSTER("5", "poster"),
/**
* 海报字体
*/
POSTER_FONT("6", "poster_font");
/**
* 媒体类型
......@@ -22,7 +30,7 @@ public enum MediaType {
String mediaType;
/**
* 0 图片(image)、1 语音(voice)、2 视频(video),3 普通文件(file) 4 文本
* 0 图片(image)、1 语音(voice)、2 视频(video),3 普通文件(file) 4 文本 5 海报 6 海报字体
*/
String type;
......
......@@ -3,75 +3,23 @@ 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.math.BigDecimal;
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;
import java.util.stream.Stream;
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();
}*/
}
......@@ -90,7 +38,7 @@ public class ImageUtils {
newWidth = oldWidth / size;
newHeight = oldHeight / size;
}
BufferedImage newBufferedImage = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);
BufferedImage newBufferedImage = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_ARGB);
Graphics2D newGraphics2D = newBufferedImage.createGraphics();
newGraphics2D.setBackground(Color.WHITE);
newGraphics2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
......@@ -184,12 +132,12 @@ public class ImageUtils {
}
int i = 0;
for (i = 0; i < directionNum; i++) {
byte bytes[] = cropImage(bufferedImage, 0, i * directionValue, width, directionValue);
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);
byte[] bytes = cropImage(bufferedImage, 0, height - directionSurplus, width, directionSurplus);
byteToFile(bytes, fileName + "-" + (i + 1), "jpg", path);
}
} else if (direction == 2) {
......@@ -199,12 +147,12 @@ public class ImageUtils {
}
int i = 0;
for (; i < directionNum; i++) {
byte bytes[] = cropImage(bufferedImage, i * directionValue, 0, directionValue, height);
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);
byte[] bytes = cropImage(bufferedImage, height - directionSurplus, 0, directionSurplus, height);
byteToFile(bytes, fileName + "-" + (i + 1), "jpg", path);
}
}
......@@ -241,10 +189,40 @@ public class ImageUtils {
return newBufferedImage;
}
/**
* 设置透明度
* @param bufferedImage
* @param alpha
* @param bufferedImageType
* @return
*/
public static BufferedImage setBufferedImageAlpha(BufferedImage bufferedImage,Integer alpha,Integer bufferedImageType){
if(alpha < 0 || alpha > 255){
throw new RuntimeException("范围错误[0,255]");
}
int width = bufferedImage.getWidth();
int height = bufferedImage.getHeight();
BufferedImage newBufferedImage = new BufferedImage(width,height, bufferedImageType);
int argb;
int oa;
int a;
int rgb;
for(int y = 0; y < height; y++){
for(int x = 0; x < width; x++){
argb = bufferedImage.getRGB(x,y);
rgb = argb & 0x00FFFFFF;
oa = argb >>> 24;
a = oa == 0?0:alpha<<24;
argb = a^rgb;
newBufferedImage.setRGB(x,y,argb);
}
}
return newBufferedImage;
}
/**
* 放大缩小
*
* @param bufferedImage
* @param enlargementTimes
* @return
......@@ -369,14 +347,23 @@ public class ImageUtils {
}
/**
* 为图片打马赛克
* @param bufferedImage
* @param pointX
* @param pointY
* @param width
* @param height
* @param level
* @return
*/
public static BufferedImage createMosaic(BufferedImage bufferedImage, Integer pointX, Integer pointY, Integer width, Integer height, Integer level) {
Integer bufferImageWidth = bufferedImage.getWidth();
Integer bufferImageHeight = bufferedImage.getHeight();
int bufferImageWidth = bufferedImage.getWidth();
int bufferImageHeight = bufferedImage.getHeight();
Integer x = pointX;
Integer y = pointY;
Integer chunkWidth = width / level;
Integer chunkHeight = height / level;
int chunkWidth = width / level;
int chunkHeight = height / level;
chunkWidth = chunkWidth == 0 ? 1 : chunkWidth;
chunkHeight = chunkHeight == 0 ? 1 : chunkHeight;
......@@ -392,8 +379,8 @@ public class ImageUtils {
y += chunkHeight;
Integer randomX = random.nextInt(chunkWidth);
Integer randomY = random.nextInt(chunkWidth);
Integer modificationX = 0;
Integer modificationY = 0;
int modificationX = 0;
int modificationY = 0;
if (x + randomX >= bufferImageWidth) {
modificationX = (x + randomX) - bufferImageWidth + 1;
}
......@@ -451,47 +438,112 @@ public class ImageUtils {
/**
* 把字符串拆成行
* @param context
* @param context 文本内容
* @param fontMetrics
* @param width
* @param height
* @param type 1 右对齐 2 居中 3 左对齐
* @param pointX 开始点的x轴坐标
* @param pointY 开始点的y轴坐标
* @param width 文本域宽度
* @param height 文本域高度
* @param wordSpace 字间距
* @param lineSpace 行间距
* @param horizontalType 1 右对齐 2 居中 3 左对齐
* @return
*/
public static List<LineText> splitContext(String context,FontMetrics fontMetrics,int pointX,int pointY,int width,int height,Integer type){
public static List<LineText> splitContext(String context,FontMetrics fontMetrics,int pointX,int pointY,int width,int height,int wordSpace,int lineSpace,Integer horizontalType,Integer verticalType){
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 currentLineWidth = 0;
//当前的高度
int currentHeight = font.getSize();
//字体宽度
int charSize = 0;
List<CharText> charTextList = new ArrayList<>();
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));
currentLineWidth += charSize;
if(currentLineWidth >= width){
returnLineList.add(new LineText(pointX,width,currentHeight,sb.toString(),currentLineWidth - charSize - wordSpace,charTextList,horizontalType));
currentHeight += font.getSize();
currentHeight += lineSpace;
currentLineWidth = charSize;
charTextList = new ArrayList<>();
sb = new StringBuilder();
sb.append(c);
nowHeight += font.getSize();
size = charSize;
}else {
sb.append(c);
}
if(nowHeight > height){
charTextList.add(new CharText(currentLineWidth - charSize,currentHeight,c));
currentLineWidth += wordSpace;
sb.append(c);
if(currentHeight > height){
sb = new StringBuilder();
break;
}
}
if(sb.length() > 0){
returnLineList.add(new LineText(pointX,width,pointY + nowHeight,sb.toString(),size,type));
returnLineList.add(new LineText(pointX,width,currentHeight,sb.toString(),currentLineWidth - wordSpace,charTextList,horizontalType));
}
if(verticalType.equals(2)){
int allHeight = returnLineList.size()* font.getSize() + lineSpace * returnLineList.size() - 1;
pointY = (height - allHeight)/2 + pointY;
}else if (verticalType.equals(3)){
int allHeight = returnLineList.size()* font.getSize() + lineSpace * returnLineList.size() - 1;
pointY = pointY + height - allHeight;
}
int finalPointY = pointY;
returnLineList.forEach(lineText -> {
lineText.setPointY(finalPointY + lineText.getPointY());
lineText.getCharTextList().forEach(charText -> {
charText.setPointY(lineText.getPointY());
});
});
return returnLineList;
}
/**
* 旋转图片
* @param bufferedImage
* @param angle
* @return
*/
public static BufferedImage rotateImage(BufferedImage bufferedImage,double angle){
Rectangle rectangle = getRotateRectangle(bufferedImage.getWidth(),bufferedImage.getHeight(),angle);
BufferedImage image = new BufferedImage((int) rectangle.getWidth(),(int) rectangle.getHeight(), BufferedImage.TYPE_4BYTE_ABGR);
Graphics2D graphics2D = image.createGraphics();
graphics2D.translate((rectangle.getWidth() - bufferedImage.getWidth()) / 2,(rectangle.getHeight() - bufferedImage.getHeight()) / 2);
graphics2D.rotate(Math.toRadians(angle), BigDecimal.valueOf(bufferedImage.getWidth()/2).doubleValue(),BigDecimal.valueOf(bufferedImage.getHeight()/2).doubleValue());
graphics2D.drawImage(bufferedImage,null,0,0);
return image;
}
public static Rectangle getRotateRectangle(double width,double height,double angle){
if (angle >= 90) {
if((int) angle / 90 % 2 == 1){
double temp = height;
height = width;
width = temp;
}
angle = angle % 90;
}
double j1Angle = Math.atan(height / width);
angle = Math.toRadians(angle);
double r = Math.sqrt(Math.pow(width,2)+Math.pow(height,2)) / 2;
double newWidth = Math.cos(j1Angle - angle) * r * 2;
double newHeight = Math.sin(j1Angle + angle) * r * 2;
newHeight = Math.abs(newHeight);
newWidth = Math.abs(newWidth);
return new Rectangle(0,0,(int) newWidth,(int) newHeight);
}
/**
* 解析16进制颜色
* @param value
* @return
*/
public static Color getColor(String value){
if(!value.startsWith("#")){
throw new RuntimeException("格式错误");
......@@ -499,6 +551,16 @@ public class ImageUtils {
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 Color getColor(String value,Integer alpha){
if(alpha == null){
return getColor(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),alpha);
}
public static FontMetrics getFontMetrics(Font font){
return J_LABEL.getFontMetrics(font);
......@@ -506,46 +568,114 @@ public class ImageUtils {
public static class LineText{
private final Integer pointX;
private Integer pointX;
private final Integer pointY;
private Integer pointY;
private final String text;
private String text;
private final Integer length;
private Integer length;
public LineText(Integer pointX,Integer width,Integer height,String text,Integer length,Integer type){
private List<CharText> charTextList;
public LineText(Integer pointX,Integer width,Integer pointY,String text,Integer length,List<CharText> charTextList,Integer type){
this.text = text;
this.length = length;
this.pointY = height;
this.pointY = pointY;
if(type.equals(1)){
this.pointX = pointX;
}else if(type.equals(2)){
this.pointX = (pointX+width - length)/2;
this.pointX = pointX+(width - length)/2;
}else if(type.equals(3)){
this.pointX = pointX+width - length;
this.pointX = pointX + width - length;
}else {
throw new RuntimeException("不支持的类型");
}
charTextList.forEach(charText -> {
charText.setPointX(this.pointX + charText.getPointX());
});
this.charTextList = charTextList;
}
public Integer getPointX() {
return pointX;
}
public void setPointX(Integer pointX) {
this.pointX = pointX;
}
public Integer getPointY() {
return pointY;
}
public void setPointY(Integer pointY) {
this.pointY = pointY;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public Integer getLength() {
return length;
}
public void setLength(Integer length) {
this.length = length;
}
public List<CharText> getCharTextList() {
return charTextList;
}
public void setCharTextList(List<CharText> charTextList) {
this.charTextList = charTextList;
}
}
public static class CharText{
private Integer pointX;
private Integer pointY;
private Character value;
public CharText(Integer pointX,Integer pointY,Character value){
this.pointX = pointX;
this.pointY = pointY;
this.value = value;
}
public Integer getPointX() {
return pointX;
}
public void setPointX(Integer pointX) {
this.pointX = pointX;
}
public Integer getPointY() {
return pointY;
}
public void setPointY(Integer pointY) {
this.pointY = pointY;
}
public Character getValue() {
return value;
}
public void setValue(Character value) {
this.value = value;
}
}
}
......@@ -57,7 +57,7 @@ public class WePoster extends BaseEntity {
private Long type;
@TableField
@ApiModelProperty(value = "海报状态 1 启用 0 关闭")
@ApiModelProperty(value = "海报状态 0 启用 1 关闭")
private Integer delFlag;
@TableField
......@@ -68,6 +68,14 @@ public class WePoster extends BaseEntity {
@ApiModelProperty(value = "海报背景高度")
private Integer height;
@TableField
@ApiModelProperty("资源类型")
private String mediaType;
@TableField
@ApiModelProperty("分类id")
private Long categoryId;
/**
* 海报组件数组
*/
......
......@@ -50,6 +50,14 @@ public class WePosterFont extends BaseEntity {
* 状态
*/
@TableField(value = "del_flag")
@ApiModelProperty(value = "1 启用 0 关闭")
@ApiModelProperty(value = "0 启用 1 关闭")
private Integer delFlag;
@TableField
@ApiModelProperty("资源类型")
private String mediaType;
@TableField
@ApiModelProperty("分类id")
private Long categoryId;
}
......@@ -84,8 +84,15 @@ public class WePosterSubassembly extends BaseEntity {
* 字体对齐方式 0 左对齐 1居中 2右对齐
*/
@TableField
@ApiModelProperty(value = "字体对齐方式 0 左对齐 1居中 2右对齐")
private Integer fontTextAlign;
@ApiModelProperty(value = "字体对齐方式 1 左对齐 2 居中 3右对齐")
private Integer fontTextAlign = 2;
/**
* 字体垂直对齐方式 0 上对齐 1居中 2下对齐
*/
@TableField
@ApiModelProperty(value = "字体垂直对齐方式 1 上对齐 2 居中 3 下对齐")
private Integer verticalType = 2;
/**
* 图片网络地址
......@@ -95,7 +102,7 @@ public class WePosterSubassembly extends BaseEntity {
private String imgPath;
@TableField
@ApiModelProperty(value = "1 启用 0 删除")
@ApiModelProperty(value = "0 启用 1 删除")
private Integer delFlag;
/**
......@@ -105,6 +112,29 @@ public class WePosterSubassembly extends BaseEntity {
@ApiModelProperty(value = "文本内容")
private String content;
@TableField
@ApiModelProperty("字间距")
private Integer wordSpace = 0;
@TableField
@ApiModelProperty("行间距")
private Integer lineSpace = 0;
@TableField
@ApiModelProperty("透明度[0,255]")
private Integer alpha;
@TableField
@ApiModelProperty("旋转角度(顺时针)")
private Integer rotate;
@TableField
@ApiModelProperty("字体类型 0 通常 1 粗体 2 斜体")
private Integer fontStyle = 0;
@TableField(value = "`order`")
@ApiModelProperty("顺序排序")
private Integer order;
/**
* 字体实体
*/
......
......@@ -13,10 +13,11 @@ public interface IWePosterFontService extends IService<WePosterFont> {
/**
* 获取字体
* @param id
* @param size
* @param id 字体id
* @param size 字体大小
* @param fontStyle 字体类型 0 通常 1 粗体 2 斜体
* @return
*/
public Font getFont(Long id,Integer size);
public Font getFont(Long id,Integer size,Integer fontStyle);
}
package com.linkwechat.wecom.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.linkwechat.common.core.domain.AjaxResult;
import com.linkwechat.wecom.domain.WePoster;
import java.util.List;
/**
* 海报
* @author ws
......@@ -16,6 +19,14 @@ public interface IWePosterService extends IService<WePoster> {
*/
public WePoster selectOne(Long id);
/**
* 列表查询海报
* @param categoryId
* @param name
* @return
*/
public List<WePoster> list(Long categoryId, String name);
/**
* 生成海报图片地址
......
package com.linkwechat.wecom.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.linkwechat.common.utils.html.EscapeUtil;
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 lombok.extern.java.Log;
import lombok.extern.log4j.Log4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
......@@ -22,8 +25,24 @@ import java.util.concurrent.ConcurrentHashMap;
* @author ws
*/
@Service
@Log
public class WePosterFontServiceImpl extends ServiceImpl<WePosterFontMapper,WePosterFont> implements IWePosterFontService {
private static Font DEFAULT_FONT;
static {
try {
DEFAULT_FONT = Font.createFont(Font.TRUETYPE_FONT,WePosterFontServiceImpl.class.getResourceAsStream("/font/default.ttf"));
log.info("字体文件读取成功");
} catch (FontFormatException e) {
e.printStackTrace();
log.info("字体加载失败");
} catch (IOException e) {
e.printStackTrace();
log.info("字体文件读取失败");
}
}
@Resource
private WePosterFontMapper wePosterFontMapper;
......@@ -34,15 +53,16 @@ public class WePosterFontServiceImpl extends ServiceImpl<WePosterFontMapper,WePo
private final Map<Long, Font> FONT_MAP = new ConcurrentHashMap<>();
/**
* 获取字体
*
* @param id
* @param size
* @return
*/
@Override
public Font getFont(Long id, Integer size) {
public Font getFont(Long id, Integer size,Integer fontStyle) {
if(id == null || id.equals(0L)){
if(fontStyle > 0){
return DEFAULT_FONT.deriveFont(fontStyle.equals(1)?Font.BOLD:Font.ITALIC,(float)size);
}else {
return DEFAULT_FONT.deriveFont((float)size);
}
}
WePosterFont posterFont = this.getById(id);
if(posterFont == null){
throw new RuntimeException("字体id为:"+id+"的字体不存在");
......
package com.linkwechat.wecom.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.linkwechat.common.config.RuoYiConfig;
import com.linkwechat.common.config.ServerConfig;
import com.linkwechat.common.utils.file.FileUploadUtils;
import com.linkwechat.common.utils.file.FileUtils;
import com.linkwechat.common.utils.img.ImageUtils;
......@@ -28,10 +30,8 @@ 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.*;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
......@@ -51,6 +51,9 @@ public class WePosterServiceImpl extends ServiceImpl<WePosterMapper, WePoster> i
@Resource
private IWePosterFontService posterFontService;
@Resource
private ServerConfig serverConfig;
/**
* 查询一条
......@@ -62,7 +65,7 @@ public class WePosterServiceImpl extends ServiceImpl<WePosterMapper, WePoster> i
public WePoster selectOne(Long id) {
WePoster poster = this.lambdaQuery()
.eq(WePoster::getId, id)
.eq(WePoster::getDelFlag, 1)
.eq(WePoster::getDelFlag, 0)
.list().get(0);
if (poster == null) {
return null;
......@@ -89,6 +92,18 @@ public class WePosterServiceImpl extends ServiceImpl<WePosterMapper, WePoster> i
return poster;
}
@Override
public List<WePoster> list(Long categoryId, String name) {
List<WePoster> fontList = this.lambdaQuery()
.eq(WePoster::getDelFlag,0)
.eq(categoryId != null,WePoster::getCategoryId,categoryId)
.like(com.linkwechat.common.utils.StringUtils.isNotBlank(name),WePoster::getTitle,name)
.orderByDesc(WePoster::getCreateTime)
.list();
return fontList;
}
/**
* 生成海报图片地址
*
......@@ -97,18 +112,21 @@ public class WePosterServiceImpl extends ServiceImpl<WePosterMapper, WePoster> i
*/
@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());
}));
Map<Long, Font> fontMap = poster.getPosterSubassemblyList().stream().filter(wePosterSubassembly -> wePosterSubassembly.getType().equals(1))
.peek(wePosterSubassembly -> {
if(wePosterSubassembly.getFontId() == null){
wePosterSubassembly.setFontId(0L);
}
})
.collect(Collectors.toMap(WePosterSubassembly::getFontId, wePosterSubassembly -> posterFontService.getFont(wePosterSubassembly.getFontId(), wePosterSubassembly.getFontSize(),wePosterSubassembly.getFontStyle())));
Map<String, NetFileUtils.FileCallable> fileCallableMap = poster.getPosterSubassemblyList().stream().filter(wePosterSubassembly -> StringUtils.isNotBlank(wePosterSubassembly.getImgPath())).distinct().collect(Collectors.toMap(WePosterSubassembly::getImgPath, wePosterSubassembly -> 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 -> {
Map<String, BufferedImage> bufferedImageMap = fileCallableMap.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, stringFileCallableEntry -> {
try {
return ImageIO.read(new ByteArrayInputStream(NetFileUtils.getByteArrayOutputStream(stringFileCallableEntry.getValue(), false).toByteArray()));
return ImageUtils.copyBufferedImage(ImageIO.read(new ByteArrayInputStream(Objects.requireNonNull(NetFileUtils.getByteArrayOutputStream(stringFileCallableEntry.getValue(), false)).toByteArray())),BufferedImage.TYPE_INT_ARGB);
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException("图片读取错误");
......@@ -118,35 +136,48 @@ public class WePosterServiceImpl extends ServiceImpl<WePosterMapper, WePoster> i
poster.setWidth(backgroundImg.getWidth());
poster.setHeight(backgroundImg.getHeight());
poster.getPosterSubassemblyList().forEach(wePosterSubassembly -> {
if (wePosterSubassembly.getFontId() != null) {
if (wePosterSubassembly.getType().equals(1)) {
Font font = fontMap.get(wePosterSubassembly.getFontId());
FontMetrics fontMetrics = ImageUtils.getFontMetrics(font);
Color color;
if (StringUtils.isNotBlank(wePosterSubassembly.getFontColor())) {
color = ImageUtils.getColor(wePosterSubassembly.getFontColor());
color = ImageUtils.getColor(wePosterSubassembly.getFontColor(),wePosterSubassembly.getAlpha());
} else {
color = Color.BLACK;
}
List<ImageUtils.LineText> lineTextList = ImageUtils.splitContext(wePosterSubassembly.getContent(), fontMetrics, wePosterSubassembly.getLeft(), wePosterSubassembly.getTop(), wePosterSubassembly.getWidth(), wePosterSubassembly.getHeight(), wePosterSubassembly.getFontTextAlign());
List<ImageUtils.LineText> lineTextList = ImageUtils.splitContext(wePosterSubassembly.getContent(), fontMetrics, wePosterSubassembly.getLeft(), wePosterSubassembly.getTop(), wePosterSubassembly.getWidth(), wePosterSubassembly.getHeight(),wePosterSubassembly.getWordSpace(),wePosterSubassembly.getLineSpace(), wePosterSubassembly.getFontTextAlign(),wePosterSubassembly.getVerticalType());
lineTextList.forEach(lineText -> {
ImageUtils.writeFontBufferedImage(backgroundImg, lineText.getText(), lineText.getPointX(), lineText.getPointY(), font, color);
});
lineText.getCharTextList().forEach(charText -> {
ImageUtils.writeFontBufferedImage(backgroundImg, charText.getValue().toString(), charText.getPointX(), charText.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());
if (wePosterSubassembly.getAlpha() != null && wePosterSubassembly.getAlpha() >= 0){
bufferedImage = ImageUtils.setBufferedImageAlpha(bufferedImage,wePosterSubassembly.getAlpha(),BufferedImage.TYPE_INT_ARGB);
}
bufferedImage = ImageUtils.fixedDimensionBufferedImage(bufferedImage, BufferedImage.TYPE_INT_ARGB, wePosterSubassembly.getWidth(), wePosterSubassembly.getHeight());
if(wePosterSubassembly.getRotate() == null){
ImageUtils.mergeBufferedImage(backgroundImg, bufferedImage, wePosterSubassembly.getLeft(), wePosterSubassembly.getTop());
}else {
int x = wePosterSubassembly.getLeft() + bufferedImage.getWidth()/2;
int y = wePosterSubassembly.getTop() + bufferedImage.getHeight()/2;
bufferedImage = ImageUtils.rotateImage(bufferedImage,wePosterSubassembly.getRotate());
x = x - bufferedImage.getWidth() / 2;
y = y - bufferedImage.getHeight() / 2;
ImageUtils.mergeBufferedImage(backgroundImg, bufferedImage, x, y);
}
}
});
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
try {
ImageIO.write(backgroundImg, "jpg", byteArrayOutputStream);
ImageIO.write(backgroundImg, "png", byteArrayOutputStream);
NetFileUtils.StreamMultipartFile streamMultipartFile = new NetFileUtils.StreamMultipartFile(System.currentTimeMillis()+".jpg",byteArrayOutputStream.toByteArray());
byteArrayOutputStream.close();
String path = FileUploadUtils.uploadFile(streamMultipartFile);
poster.setSampleImgPath(path);
poster.setSampleImgPath(serverConfig.getUrl() + path);
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException("图片生成错误");
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!