案例:
底图:
色值转换工具: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
@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
static BufferedImage roundImage(BufferedImage image, int targetSize, int cornerRadius) throws Exception {
BufferedImage outputImage = new BufferedImage(targetSize, targetSize, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = outputImage.createGraphics();
g2.setComposite(AlphaComposite.Src);
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.setColor(Color.WHITE);
g2.fill(new RoundRectangle2D.Float(0, 0, targetSize, targetSize, cornerRadius, cornerRadius));
g2.setComposite(AlphaComposite.SrcAtop);
g2.drawImage(image, 0, 0, null);
g2.dispose();
return outputImage;
}
/**https替换http*/
private static String convert2HttpUrl(String url){
url = url.contains("https") ? url.replace("https", "http") : url;
return url;
}
/**读取web图片*/
private static BufferedImage loadWebUrlImage(String url) throws IOException {
ByteArrayInputStream in = new ByteArrayInputStream(HttpUtil.getBytes(url));
BufferedImage bufferedImage = ImageIO.read(in);
return bufferedImage;
}
/**调整图片大小 204*204*/
private static BufferedImage resize(BufferedImage bufferedImage){
BufferedImage result = new BufferedImage(284, 284,BufferedImage.TYPE_INT_RGB);
Graphics graphics = result.getGraphics();
graphics.drawImage(bufferedImage.getScaledInstance(284, 284,Image.SCALE_SMOOTH), 0, 0, null);
graphics.dispose();
return result;
}
public static Double fen2RMByuanDouble(Long fen) {
if (fen == null) {
return 0D;
} else {
BigDecimal amount = new BigDecimal(fen);
amount = amount.divide(new BigDecimal(100));
return amount.doubleValue();
}
}
private static int getStrWidth(Font font, String text) {
FontMetrics fontMetrics = FontDesignMetrics.getMetrics(font);
return fontMetrics.stringWidth(text);
}
/**
* 2D绘图
* @param backImage 背景图
* @param list 有序图片组件(ImageParam、TextParam),组件图层从低到高
* @return 图片的web地址
* @throws IOException
*/
private static String graphics2DImg(ActivityShareImageType activityType,BufferedImage backImage, LinkedList list ) throws IOException{
// 图片的高/宽度
int bwidth = backImage.getWidth();
int bheight = backImage.getHeight();
if ("特价活动分享图".equals(activityType.type)){
bheight = bheight*2-100;
}
int alphaType = BufferedImage.TYPE_INT_RGB;
// 画板图片
BufferedImage backgroundImage = new BufferedImage(bwidth, bheight, alphaType);
Graphics2D graphics2D = backgroundImage.createGraphics();
graphics2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
graphics2D.drawImage(backImage.getScaledInstance(bwidth, bheight, Image.SCALE_SMOOTH), 0, 0, null);
graphics2D.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, 1));
if(list!=null){
for(Object obj:list){
if( obj instanceof ImageParam){
drawImageParam((ImageParam)obj,graphics2D);
}else if(obj instanceof TextParam){
drawTextParam((TextParam) obj,graphics2D);
}else{
throw new BizException(-1,"生成图片参数异常");
}
}
}
String imgUrl = writeFileAndUpload(backgroundImage);
graphics2D.dispose();
return imgUrl;
}
private static void drawImageParam(ImageParam param,Graphics2D graphics2D){
int triangleWidth = param.getBufferedImage().getWidth();
int triangleHeight = param.getBufferedImage().getHeight();
graphics2D.drawImage(param.getBufferedImage().getScaledInstance(triangleWidth, triangleHeight, Image.SCALE_SMOOTH), param.getX(), param.getY(), triangleWidth, triangleHeight, null);
}
private static String writeFileAndUpload(BufferedImage backgroundImage) throws IOException {
String folder = System.getProperty("java.io.tmpdir");
String filePath = folder + UUID.randomUUID().toString() + ".png";
ImageIO.write(backgroundImage, "png", new File(filePath));
return "/" + QiNiuCdnUtil.uploadToQiNiu(filePath, "s/p/product_v2/");
}
/**
* 上传文件到七牛cdn
*
* @param tempImagePath
* @param qiNiuWxacodeImagePath
* @return
*/
public static String uploadToQiNiu(String tempImagePath, String qiNiuWxacodeImagePath) {
if(StringHelper.isEmpty(tempImagePath)){
return null;
}
try {
Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
String upToken = auth.uploadToken(BUCKET);
//这里的key参数就是文件的路径
String qiNiuImagePath = getQiNiuImagePath(tempImagePath,qiNiuWxacodeImagePath);
Response response = QINIU_UPLOAD_MANAGER.put(tempImagePath, qiNiuImagePath, upToken);
//解析上传成功的结果
DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
//返回文件路径,并记录
LOGGER.info("上传图片成功,图片路径{}","http://image.baidu.com/" + putRet.key);
return putRet.key;
} catch (QiniuException ex) {
Response r = ex.response;
LOGGER.error("上传图片到七牛云失败", ex);
try {
LOGGER.error(r.bodyString());
return null;
} catch (QiniuException ex2) {
LOGGER.error("上传图片到七牛云失败", ex2);
return null;
}
}
finally {
try {
//上传完成后删除
new File(tempImagePath).delete();
}
catch (Exception e) {
LOGGER.error(e.getMessage(),e);
}
}
}