案例:
底图:
色值转换工具:http://www.atool.org/colorpicker.php
代码:
public interface ActivityShareImageServise {
/**生成活动分享图*/
String generateActivityShareImage(ActivityShareImageType activityType,Integer itemId) throws Exception;
/**
* 生成分享图片组件
* @param activityType
* @param itemId 商品id
* @return 有序组件(ImageParam、TextParam),绘图时有序添加组件
* @throws IOException
*/
LinkedList<Object> generateimgComponent(ActivityShareImageType activityType,Integer itemId) throws Exception;
}
/**
* 活动分享图类型
*/
public enum ActivityShareImageType {
TEJIA_ACTIVITY("特价活动分享图","images/tejia/tejia-background.jpg"),
CUTPRICE_ACTIVITY_POOL_COLOR("砍价活动分享图策略池-色彩","images/cutpricepool/color.png"),;
ActivityShareImageType(String type,String imgPath){
this.type = type;
this.imgPath = imgPath;
}
public String type;
public String imgPath;
}
@Override
public String generateActivityShareImage(ActivityShareImageType activityType, Integer itemId) throws Exception{
try {
BufferedImage backImage = loadClassPathImage(activityType.imgPath);
LinkedList list = generateimgComponent(activityType,itemId);
return graphics2DImg(activityType,backImage,list);
}catch (Exception e){ //避免创建分享图
logger.error("生成活动分析卡片图异常:{}",e.getMessage(),e);
throw new BizException(0,"创建活动分享卡片图异常");
}
}
//加载底图
private BufferedImage loadClassPathImage(String classPath) {
BufferedImage bufferedImage = null;
try {
InputStream resourceAsStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(classPath);
bufferedImage = ImageIO.read(resourceAsStream);
} catch (IOException e) {
//e.printStackTrace();
logger.error(e.getMessage(),e);;
}
return bufferedImage;
}
@Override
public LinkedList<Object> generateimgComponent(ActivityShareImageType activityType,
Integer itemId) throws Exception{
LinkedList<Object> list = new LinkedList<>();
switch (activityType){
case TEJIA_ACTIVITY:{
BufferedImage backImage = loadClassPathImage(activityType.imgPath);
//白色底图
BufferedImage whiteImage = new BufferedImage(backImage.getWidth()-20*2, backImage.getHeight()-20,BufferedImage.TYPE_INT_BGR);
Graphics2D graphics = whiteImage.createGraphics();
graphics.setBackground(Color.white);
graphics.clearRect(0, 0, backImage.getWidth()-20*2, backImage.getHeight()-20);
graphics.dispose();
whiteImage = roundImage(whiteImage,whiteImage.getWidth(),30);
ImageParam whiteParam = new ImageParam(whiteImage,