前言
微信後臺生成海報一般都是一個模板寫死,然後就完事了,過了不久讓修改個模板,就又要看半天,還要考慮是否重新複製一份改一改,越來越多的重複代碼,全在一個圖片類裏,然後就越來越亂。這兩天用設計模式處理了一下,讓以後修改模板,新增模板更舒服一點。有第三方好用的輕量級的實現,還請留言。感激!!
博客園鏈接
效果圖
簡單註解實現繪製
基於java8 和 lombok 的小輪子
Maven 引入【github直接clone源碼,更方便定製修改】
<!-- https://mvnrepository.com/artifact/com.github.quaintclever/easyposter -->
<dependency>
<groupId>com.github.quaintclever</groupId>
<artifactId>easyposter</artifactId>
<version>1.2</version>
</dependency>
Gradle
// https://mvnrepository.com/artifact/com.github.quaintclever/easyposter
compile group: 'com.github.quaintclever', name: 'easyposter', version: '1.2'
海報定義類
/**
* @author quaint
* @date 30 March 2020
* @since 1.0
*/
@EqualsAndHashCode(callSuper = true)
@Data
@Builder
public class SamplePoster extends AbstractDefaultPoster {
/**
* 背景圖
*/
@PosterBackground(width = 666,height = 365)
private BufferedImage backgroundImage;
/**
* 頭像
*/
@PosterImageCss(position = {27,27},width = 36, height = 36, circle = true)
private BufferedImage head;
/**
* 暱稱
*/
@PosterFontCss(position = {71,32}, color = {255,255,255})
private String nickName;
/**
* 廣告語
*/
@PosterFontCss(position = {27,70},center = true, size = 22, color = {255,255,255}, canNewLine={1,221,7})
private String slogan;
/**
* 主圖
*/
@PosterImageCss(position = {27,172},width = 168,height = 168)
private BufferedImage mainImage;
@Tolerate
public SamplePoster() {}
}
海報繪製
/**
* 繪製海報本地測試
* @author quaint
* @date 21 February 2020
* @since 1.0
*/
public class PosterTest {
public static void main(String[] args) throws Exception{
// 測試,圖片添加到resources/image下 ClassPathResource 需要引入spring
BufferedImage background = ImageIO.read(new ClassPathResource("image/yayi.png").getInputStream());
BufferedImage head = ImageIO.read(new ClassPathResource("image/headimage.jpg").getInputStream());
SamplePoster poster = SamplePoster.builder()
.backgroundImage(background)
.head(head)
.nickName("Quaint")
.slogan("命運多舛,癡迷淡然。揮別了青春,數不盡的車站。甘於平凡,卻不甘平凡地潰敗。")
.mainImage(head)
.build();
PosterDefaultImpl<SamplePoster> impl = new PosterDefaultImpl<>();
BufferedImage test = impl.annotationDrawPoster(poster).draw(null);
ImageIO.write(test,"png",new FileOutputStream("annTest.png"));
}
}