原创

java海报生成工具类

作者:cndz 围观群众:659 更新于 标签:java工具类海报生成工具类海报生成代码实例

简介

海报生成工具类,代码实例,使用java代码生成海报。

效果

海报生成效果图片

代码

实体类

 package test.utils.poster;

import java.awt.*;
import java.io.Serializable;

/**
 * @author:zzy
 * @date:Created in 2023/7/29 17:25
 * @modified By:zzy
 */
public class Poster implements Serializable {
    private int width;//海报的宽(像素为单位)
    private int height;//海报的高

    //顶部图片
    private String topUrl;
    private int topX;
    private int topY;
    private int topWidth;
    private int topHeight;
    //标题样式
    private String title;
    private Font titleFont;
    private Color titleColor;
    private int titleX;
    private int titleY;

    //测评结果标题
    private String result;
    private Font resultFont;
    private Color resultColor;
    private int resultX;
    private int resultY;

    //测评结果描述
    private String result_content;
    private Font result_contentFont;
    private Color result_contentColor;
    private int result_contentX;
    private int result_contentY;

    /**
     * @return the result
     */
    public String getResult() {
        return result;
    }

    /**
     * @param result the result to set
     */
    public void setResult(String result) {
        this.result = result;
    }

    /**
     * @return the resultFont
     */
    public Font getResultFont() {
        return resultFont;
    }

    /**
     * @param resultFont the resultFont to set
     */
    public void setResultFont(Font resultFont) {
        this.resultFont = resultFont;
    }

    /**
     * @return the resultColor
     */
    public Color getResultColor() {
        return resultColor;
    }

    /**
     * @param resultColor the resultColor to set
     */
    public void setResultColor(Color resultColor) {
        this.resultColor = resultColor;
    }

    /**
     * @return the resultX
     */
    public int getResultX() {
        return resultX;
    }

    /**
     * @param resultX the resultX to set
     */
    public void setResultX(int resultX) {
        this.resultX = resultX;
    }

    /**
     * @return the resultY
     */
    public int getResultY() {
        return resultY;
    }

    /**
     * @param resultY the resultY to set
     */
    public void setResultY(int resultY) {
        this.resultY = resultY;
    }

    /**
     * @return the result_content
     */
    public String getResult_content() {
        return result_content;
    }

    /**
     * @param result_content the result_content to set
     */
    public void setResult_content(String result_content) {
        this.result_content = result_content;
    }

    /**
     * @return the result_contentFont
     */
    public Font getResult_contentFont() {
        return result_contentFont;
    }

    /**
     * @param result_contentFont the result_contentFont to set
     */
    public void setResult_contentFont(Font result_contentFont) {
        this.result_contentFont = result_contentFont;
    }

    /**
     * @return the result_contentColor
     */
    public Color getResult_contentColor() {
        return result_contentColor;
    }

    /**
     * @param result_contentColor the result_contentColor to set
     */
    public void setResult_contentColor(Color result_contentColor) {
        this.result_contentColor = result_contentColor;
    }

    /**
     * @return the result_contentX
     */
    public int getResult_contentX() {
        return result_contentX;
    }

    /**
     * @param result_contentX the result_contentX to set
     */
    public void setResult_contentX(int result_contentX) {
        this.result_contentX = result_contentX;
    }

    /**
     * @return the result_contentY
     */
    public int getResult_contentY() {
        return result_contentY;
    }

    /**
     * @param result_contentY the result_contentY to set
     */
    public void setResult_contentY(int result_contentY) {
        this.result_contentY = result_contentY;
    }

    //小程序码
    private String qrCodeUrl;
    private int qrCodeX;
    private int qrCodeY;
    private int qrCodeWidth;
    private int qrCodeHeight;
    //提示1
    private String tip1;
    private Font tip1Font;
    private Color tip1Color;
    private int tip1X;
    private int tip1Y;
    //提示2
    private String tip2;
    private Font tip2Font;
    private Color tip2Color;
    private int tip2X;
    private int tip2Y;

    public int getWidth() {
        return width;
    }

    public void setWidth(int width) {
        this.width = width;
    }

    public int getHeight() {
        return height;
    }

    public void setHeight(int height) {
        this.height = height;
    }

    public String getTopUrl() {
        return topUrl;
    }

    public void setTopUrl(String topUrl) {
        this.topUrl = topUrl;
    }

    public int getTopX() {
        return topX;
    }

    public void setTopX(int topX) {
        this.topX = topX;
    }

    public int getTopY() {
        return topY;
    }

    public void setTopY(int topY) {
        this.topY = topY;
    }

    public int getTopWidth() {
        return topWidth;
    }

    public void setTopWidth(int topWidth) {
        this.topWidth = topWidth;
    }

    public int getTopHeight() {
        return topHeight;
    }

    public void setTopHeight(int topHeight) {
        this.topHeight = topHeight;
    }


    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public Font getTitleFont() {
        return titleFont;
    }

    public void setTitleFont(Font titleFont) {
        this.titleFont = titleFont;
    }

    public Color getTitleColor() {
        return titleColor;
    }

    public void setTitleColor(Color titleColor) {
        this.titleColor = titleColor;
    }

    public int getTitleX() {
        return titleX;
    }

    public void setTitleX(int titleX) {
        this.titleX = titleX;
    }

    public int getTitleY() {
        return titleY;
    }

    public void setTitleY(int titleY) {
        this.titleY = titleY;
    }

    public String getQrCodeUrl() {
        return qrCodeUrl;
    }

    public void setQrCodeUrl(String qrCodeUrl) {
        this.qrCodeUrl = qrCodeUrl;
    }

    public int getQrCodeX() {
        return qrCodeX;
    }

    public void setQrCodeX(int qrCodeX) {
        this.qrCodeX = qrCodeX;
    }

    public int getQrCodeY() {
        return qrCodeY;
    }

    public void setQrCodeY(int qrCodeY) {
        this.qrCodeY = qrCodeY;
    }

    public int getQrCodeWidth() {
        return qrCodeWidth;
    }

    public void setQrCodeWidth(int qrCodeWidth) {
        this.qrCodeWidth = qrCodeWidth;
    }

    public int getQrCodeHeight() {
        return qrCodeHeight;
    }

    public void setQrCodeHeight(int qrCodeHeight) {
        this.qrCodeHeight = qrCodeHeight;
    }

    public String getTip1() {
        return tip1;
    }

    public void setTip1(String tip1) {
        this.tip1 = tip1;
    }

    public Font getTip1Font() {
        return tip1Font;
    }

    public void setTip1Font(Font tip1Font) {
        this.tip1Font = tip1Font;
    }

    public Color getTip1Color() {
        return tip1Color;
    }

    public void setTip1Color(Color tip1Color) {
        this.tip1Color = tip1Color;
    }

    public int getTip1X() {
        return tip1X;
    }

    public void setTip1X(int tip1X) {
        this.tip1X = tip1X;
    }

    public int getTip1Y() {
        return tip1Y;
    }

    public void setTip1Y(int tip1Y) {
        this.tip1Y = tip1Y;
    }

    public String getTip2() {
        return tip2;
    }

    public void setTip2(String tip2) {
        this.tip2 = tip2;
    }

    public Font getTip2Font() {
        return tip2Font;
    }

    public void setTip2Font(Font tip2Font) {
        this.tip2Font = tip2Font;
    }

    public Color getTip2Color() {
        return tip2Color;
    }

    public void setTip2Color(Color tip2Color) {
        this.tip2Color = tip2Color;
    }

    public int getTip2X() {
        return tip2X;
    }

    public void setTip2X(int tip2X) {
        this.tip2X = tip2X;
    }

    public int getTip2Y() {
        return tip2Y;
    }

    public void setTip2Y(int tip2Y) {
        this.tip2Y = tip2Y;
    }


}

工具类

package top.jhone.common.utils.poster;

import sun.font.FontDesignMetrics;
import top.jhone.common.utils.FileUtils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.Ellipse2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.net.URL;

/**
 * @author:zzy
 * @date:Created in 2023/7/29 17:26
 * @modified By:zzy
 */
public class PosterUtil {
    static Poster initPoster(Poster poster_) {
        Poster poster = new Poster();
        //画布
        poster.setWidth(poster_.getWidth());
        poster.setHeight(poster_.getHeight());
        //商品
        poster.setTopUrl(poster_.getTopUrl());
        poster.setTopWidth(375); //banner图宽度填充满
        poster.setTopHeight(150);
        poster.setTopX((poster_.getWidth()-poster.getTopWidth())/2);
        int size = poster_.getWidth()/17;
        //测评结果标题
        poster.setTitle(poster_.getTitle());
        poster.setTitleColor(Color.BLACK);
        poster.setTitleFont(new Font("宋体",Font.BOLD,size));
        poster.setTitleX((poster_.getWidth()-poster_.getTitle().length()*size)/5);
        poster.setTitleY(poster.getTopY()+poster.getTopHeight()+(int)(poster_.getHeight()/10.6)-12);

        //测评说明
        poster.setResult("简介");
        poster.setResultColor(Color.GRAY);
        poster.setResultFont(new Font("宋体",Font.BOLD,18));
        poster.setResultX((poster_.getWidth()-"测评说明".length()*size)/6-15);
        poster.setResultY(poster.getTopY()+poster.getTopHeight()+(int)(poster_.getHeight()/21.3)+90);

        //测评说明描述
        poster.setResult_content(poster_.getResult_content());
        poster.setResult_contentColor(Color.BLACK);
        poster.setResult_contentFont(new Font("宋体",Font.BOLD,17));
        poster.setResult_contentX((3*size)/6+23);
        poster.setResult_contentY(poster.getTopY()+poster.getTopHeight()+(int)(poster_.getHeight()/21.3)+120);


        //小程序码
        poster.setQrCodeUrl(poster_.getQrCodeUrl());
        poster.setQrCodeWidth((int)(poster_.getWidth()/2.85));
        poster.setQrCodeHeight((int)(poster_.getWidth()/2.85));
        poster.setQrCodeX((int)(poster_.getWidth()/16.5));
        poster.setQrCodeY(poster_.getHeight()-poster.getQrCodeHeight()-(int)(poster_.getHeight()/7.68));
        //tips1
        poster.setTip1("长按识别二维码");
        poster.setTip1Color(Color.BLACK);
        poster.setTip1Font(new Font("宋体",Font.BOLD,poster_.getWidth()/21));
        poster.setTip1X(poster.getQrCodeX()+poster.getQrCodeWidth()+20);
        poster.setTip1Y(poster.getQrCodeY()+poster.getQrCodeHeight()/2+10);
        //tips2
        poster.setTip2("或扫码使用二维码");//好物与好友一起分享
        poster.setTip2Color(Color.GRAY);
        poster.setTip2Font(new Font("宋体",Font.PLAIN,poster_.getWidth()/25));
        poster.setTip2X(poster.getQrCodeX()+poster.getQrCodeWidth()+20);
        poster.setTip2Y(poster.getQrCodeY()+poster.getQrCodeHeight()/2+32);//90是这句问题与上面的间距
        return poster;
    }

    public static String drawPoster(Poster poster) throws Exception {
        long startTime = System.currentTimeMillis();
        String qrCodeUrl = poster.getQrCodeUrl();
        String goodsUrl = poster.getTopUrl();
        BufferedImage qrCodeImage = ImageIO.read(new URL(qrCodeUrl));
        BufferedImage goodsImage = ImageIO.read(new URL(goodsUrl));
        int width = poster.getWidth();
        int height = poster.getHeight();
        //画布
        BufferedImage canvas = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
        Graphics2D g = (Graphics2D) canvas.getGraphics();
        g.setBackground(Color.WHITE);//设置背景色
        g.clearRect(0, 0, width, height);

        // 设置文字抗锯齿
        g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
        g.drawImage(goodsImage.getScaledInstance(poster.getTopWidth(), poster.getTopHeight(), Image.SCALE_SMOOTH), poster.getTopX(), poster.getTopY(), null);
        //测评结果标题
        FontDesignMetrics titleMetrics = FontDesignMetrics.getMetrics(poster.getTitleFont());
        String title = poster.getTitle();
        String[] titleRows = makeLineFeed(title, titleMetrics, 360).split("\n");
        int titleY = poster.getTitleY();
        if(titleRows.length <= 1){
            g.setColor(poster.getResultColor());
            g.setFont(poster.getResult_contentFont());
            g.drawString("标题", poster.getResult_contentX(), poster.getResult_contentY());
            g.setColor(poster.getResult_contentColor());
            g.setFont(poster.getTitleFont());
            g.drawString(titleRows[0], poster.getTitleX()+30, titleY+30);
        }else{
            for(int i=0; i< titleRows.length; i++){
                g.setColor(poster.getResult_contentColor());
                g.setFont(poster.getTitleFont());
                if(i > 0){
                    titleY+=30;
                }
                if(i>1){
                    break;
                }else if(i==1){
                    g.drawString(titleRows[i].substring(0, titleRows[i].length()-3)+" ...", poster.getTitleX()+80, titleY);
                    break;
                }
                g.drawString(titleRows[i], poster.getTitleX()+80, titleY);
            }
        }
        //画测评说明
        g.setColor(poster.getResultColor());
        g.setFont(poster.getResultFont());
        g.drawString(poster.getResult(), poster.getResultX(), poster.getResultY());
        FontDesignMetrics metrics = FontDesignMetrics.getMetrics(poster.getResult_contentFont());
        String zh = poster.getResult_content();
        String[] rows = makeLineFeed(zh, metrics, 300).split("\n");
        int  y = poster.getResult_contentY();
        if(rows.length < 4){
            y+=28;
        }
        for (int i = 0; i < rows.length; i++) {
            g.setColor(poster.getResult_contentColor());
            g.setFont(poster.getResult_contentFont());
            if(i > 0){
                y+=28;
            }
            if(i>4){
                break;
            }else if(i==4){
                g.drawString(rows[i].substring(0, rows[i].length()-3)+" ...", poster.getResult_contentX()+25, y);
                break;
            }
            g.drawString(rows[i], poster.getResult_contentX()+25, y);

        }


        //画小程序码
        g.drawImage(qrCodeImage.getScaledInstance(poster.getQrCodeWidth(), poster.getQrCodeHeight(), Image.SCALE_SMOOTH),
                poster.getQrCodeX(), poster.getQrCodeY(), null);
        //画tips1
        g.setColor(poster.getTip1Color());
        g.setFont(poster.getTip1Font());
        g.drawString(poster.getTip1(), poster.getTip1X(), poster.getTip1Y());
        //画tips2
        g.setColor(poster.getTip2Color());
        g.setFont(poster.getTip2Font());
        g.drawString(poster.getTip2(), poster.getTip2X(), poster.getTip2Y());
        g.dispose();
        //测试时使用,自己使用需要自己生成逻辑
        fileName = "D:\\demo.png";
        File resultImg = new File(fileName);
        ImageIO.write(canvas, "png", resultImg);
        System.out.println("生成成功!");
        System.out.println("耗时: " + (System.currentTimeMillis()-startTime)/1000.0 + "s");
        System.out.println("生成文件路径: " + resultImg.getAbsolutePath());
        return fileName;
    }


    private static BufferedImage circle(String avatar_img,int width) throws Exception {
        BufferedImage avatar = ImageIO.read(new URL(avatar_img));
        BufferedImage newAvatar = new BufferedImage(width, width, BufferedImage.TYPE_INT_ARGB);
        Ellipse2D.Double shape = new Ellipse2D.Double(0, 0, width, width);
        Graphics2D g2 = newAvatar.createGraphics();
        newAvatar = g2.getDeviceConfiguration().createCompatibleImage(width, width, Transparency.TRANSLUCENT);
        g2 = newAvatar.createGraphics();
        g2.setComposite(AlphaComposite.Clear);
        g2.fill(new Rectangle(newAvatar.getWidth(), newAvatar.getHeight()));
        g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC, 1.0f));
        g2.setClip(shape);
        // 使用 setRenderingHint 设置抗锯齿
        g2 = newAvatar.createGraphics();
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2.fillRoundRect(0, 0,width, width, width, width);
        g2.setComposite(AlphaComposite.SrcIn);
        g2.drawImage(avatar, 0, 0, width, width, null);
        g2.dispose();
        return newAvatar;
    }

    //文本换行处理
    public static String makeLineFeed(String zh, FontDesignMetrics metrics, int max_width) {
        StringBuilder sb = new StringBuilder();
        int line_width = 0;
        for (int i = 0; i < zh.length(); i++) {
            char c = zh.charAt(i);
            sb.append(c);
            // 如果主动换行则跳过
            if (sb.toString().endsWith("\n")) {
                line_width = 0;
                continue;
            }
            // FontDesignMetrics 的 charWidth() 方法可以计算字符的宽度
            int char_width = metrics.charWidth(c);
            line_width += char_width;
            // 如果当前字符的宽度加上之前字符串的已有宽度超出了海报的最大宽度,则换行
            if (line_width >= max_width - char_width) {
                line_width = 0;
                sb.append("\n");
            }
        }
        return sb.toString();
    }

    public static String genPoster(String topUrl, String qrCodeUrl, String title, String content) throws Exception {
        Poster poster_ = new Poster();
        poster_.setWidth(375);
        poster_.setHeight(650);
        poster_.setQrCodeUrl(qrCodeUrl); //二维码
        poster_.setTopUrl(topUrl); //顶部banner
        poster_.setResult_content(content); //测评结果说明
        poster_.setTitle(title); //测评结果标题
        poster_.setTitleFont(new Font("宋体",Font.BOLD,30));

        Poster poster = PosterUtil.initPoster(poster_);
        return PosterUtil.drawPoster(poster);
    }

    public static void main(String[] args) throws Exception {
        String qrCodeUrl = "https://www.zytool.cn/generate/qrCode/2023-07-29/816787b2df094fb48b0837cf0256b87a.png"; //二维码
        String topUrl = "https://www.zytool.cn/upload/article_thumb/2023-06-24/6c230758078b4c9286934c340d5f1d7d.png"; //顶部图片
        String content = "访问者模式是一种行为型设计模式,它允许你将对通过这种方式,可以在不改变现有对象结构的情况下";
        String title = "设计模式之访问者模计模式,它允许你将对通过这种方式,可以在不改";

        System.out.println(genPoster(topUrl, qrCodeUrl, title, content));

    }
}
加入收藏