Java代码生成海报图片

话不多说,先上最终效果图

注意点:

 1.画图本身不需要额外Jar包,但是海报图中需要生成二维码,所以添加了二维码所需JAR
 2.如果生成圆角图,必须为PNG格式,踩坑之谈

package com.example.demo.utils;

import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.Ellipse2D;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.*;
/**
 * 海报图工具类
 */
public class PosterUtils {

    public static final String PING_FANG_SCREGULAR_TTF = "D:\\PingFang SC Regular.ttf";
    public static final String PING_FANG_MEDIUM_TTF = "D:\\PingFang Medium.ttf";

    /**
     * 生成分享页海报图
     *
     * @return
     * @throws Exception
     */
    public static BufferedImage createImage() throws Exception {

        //读取字体文件,设置文字字体
        InputStream regularFile = new FileInputStream(PING_FANG_SCREGULAR_TTF);
        InputStream mediumFile = new FileInputStream(PING_FANG_MEDIUM_TTF);
        Font regularFont = Font.createFont(Font.TRUETYPE_FONT, regularFile);
        Font mediumFont = Font.createFont(Font.TRUETYPE_FONT, mediumFile);

        //设置整张图片的大小
        int width = 290 * 3;
        int height = 436 * 3;
        // RGB形式
        BufferedImage bgBufImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D graphics = bgBufImage.createGraphics();
        // 设置背景色
        graphics.setBackground(Color.WHITE);
        // 通过使用当前绘图表面的背景色进行填充来清除指定的矩形。
        graphics.clearRect(0, 0, width, height);
        graphics.setBackground(new Color(255, 255, 255));
        //读取主图
        BufferedImage posterBufImage = ImageIO.read(new FileInputStream("D:\\img\\zhutu.jpg"));
        BufferedImage headImage = ImageIO.read(new FileInputStream("D:\\img\\touxiang.jpg"));
        // 画一个圆形,放置头像
        BufferedImage roundHeadImg = new BufferedImage(headImage.getWidth(), headImage.getHeight(), BufferedImage.TYPE_INT_RGB);
        Graphics2D roundHeadGraphics = roundHeadImg.createGraphics();
        Ellipse2D.Double shape = new Ellipse2D.Double(0, 0, roundHeadImg.getWidth(), roundHeadImg.getHeight());
        roundHeadGraphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        roundHeadImg = roundHeadGraphics.getDeviceConfiguration().createCompatibleImage(headImage.getWidth(),
                headImage.getHeight(), Transparency.TRANSLUCENT);
        roundHeadGraphics = roundHeadImg.createGraphics();
        // 使用 setRenderingHint 设置抗锯齿
        roundHeadGraphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        roundHeadGraphics.setClip(shape);
        roundHeadGraphics.drawImage(headImage, 0, 0, null);
        roundHeadGraphics.dispose();
        //画海报图
        graphics.drawImage(posterBufImage, 0, 0, 290 * 3, 241 * 3, null);
        //圆形头像图
        graphics.drawImage(roundHeadImg, 15 * 3, 221 * 3, 40 * 3, 40 * 3, null);
        // 用户昵称
        graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        regularFont = regularFont.deriveFont(Font.BOLD, 12 * 3);
        graphics.setFont(regularFont);
        // 设置画笔,设置Paint属性
        graphics.setPaint(new Color(102, 102, 102));
        graphics.drawString("往事如风", 60 * 3, 257 * 3);
        // 设置画笔,设置Paint属性
        mediumFont = mediumFont.deriveFont(Font.BOLD, 15 * 3);
        graphics.setPaint(new Color(51, 51, 51));
        graphics.setFont(mediumFont);
        graphics.drawString("平凡的一天", 15 * 3, 288 * 3);
        regularFont = regularFont.deriveFont(Font.BOLD, 11 * 3);
        // 设置画笔,设置Paint属性
        graphics.setPaint(new Color(102, 102, 102));
        graphics.setFont(regularFont);
        drawStringWithFontStyleLineFeed(graphics, "这是多么好美好的一天,这是多么好美好的一天这是多么好美好的一天,这是多么好美好的一天这是多么好美好的一天", 253 * 3, 15 * 3, 310 * 3, regularFont);
        //中间横线
        graphics.setPaint(new Color(229, 229, 229));
        graphics.drawLine(0, 345 * 3, 290 * 3, 345 * 3);
        // 生成二维码
        BufferedImage qrCodeImage = QRCodeUtils.encode("www.baidu.com", false);
        //二维码图
        graphics.drawImage(qrCodeImage, 15 * 3, 361 * 3, 60 * 3, 60 * 3, null);
        // 抗锯齿
        graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        // 表示这段文字在图片上的位置(x,y) 设置内容。
        regularFont = regularFont.deriveFont(Font.BOLD, 11 * 3);
        graphics.setPaint(new Color(51, 51, 51));
        graphics.setFont(regularFont);
        drawStringWithFontStyleLineFeed(graphics, "长按识别二维码\n查看精彩", 77 * 3, 85 * 3, 385 * 3, regularFont);

        //logo图
        InputStream logIputStream = new FileInputStream("D:\\img\\logo.jpg");
        BufferedImage logImage = ImageIO.read(logIputStream);
        graphics.drawImage(logImage, 230 * 3, 364 * 3, 40 * 3, 40 * 3, null);

        //字体logo
        InputStream logoFontInputStream = new FileInputStream("D:\\img\\wenzi.jpg");
        BufferedImage logFontImage = ImageIO.read(logoFontInputStream);
        graphics.drawImage(logFontImage, 225 * 3, 412 * 3, 50 * 3, 9 * 3, null);
        graphics.dispose();

        //生成圆角图 -- 不要圆角此段代码可删除
        BufferedImage outputImage = new BufferedImage(width, height, BufferedImage.TYPE_4BYTE_ABGR);
        Graphics2D g2 = outputImage.createGraphics();
        g2.setComposite(AlphaComposite.Src);
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);
        g2.fill(new RoundRectangle2D.Float(0, 0, width, height, 50,
                50));
        g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, 1.0f));
        g2.drawImage(bgBufImage, 0, 0, null);
        g2.dispose();

        return outputImage;
    }


    //写文字
    private static void drawStringWithFontStyleLineFeed(Graphics2D g, String strContent,int maxWdith, int loc_X, int loc_Y, Font font){
        g.setFont(font);
        //获取字符串 字符的总宽度
        int strWidth = getStringLength(g,strContent);
        int strHeight = getStringHeight(g);
        if(strWidth > maxWdith){
            int rowstrnum = getRowStrNum(strContent.length(),maxWdith,strWidth);
            int rows = getRows(strWidth,maxWdith);
            for (int i = 0; i < 2; i++) {
                String temp = "" ;
                //获取各行的String
                if(i == 1){
                    if(rows == 2){
                        temp = strContent.substring(i * rowstrnum);
                    }else{
                        temp = strContent.substring(i * rowstrnum,(i + 1) * rowstrnum - 1);
                        temp = "\n" + temp + "...";
                    }
                    loc_Y = loc_Y + strHeight;
                }
                if(i == 0){
                    temp = strContent.substring(0,rowstrnum);
                }
                g.drawString(temp, loc_X, loc_Y);
            }
        }else{
            //直接绘制
            g.drawString(strContent, loc_X, loc_Y);
        }
    }

    /** 获取文字总长度 */
    private static int getStringLength(Graphics g, String str) {
        char[] strcha = str.toCharArray();
        int strWidth = g.getFontMetrics().charsWidth(strcha, 0, str.length());
        return strWidth;
    }

    /** 获取字符高度 */
    private static int getStringHeight(Graphics g) {
        int height = g.getFontMetrics().getHeight();
        return height;
    }

    /** 每行的字符数 */
    private static int getRowStrNum(int strnum,int rowWidth,int strWidth){
        int rowstrnum = 0;
        rowstrnum = (rowWidth * strnum) / strWidth;
        return rowstrnum;
    }

    /** 字符行数 */
    private static int getRows(int strWidth,int rowWidth){
        int rows=0;
        if(strWidth%rowWidth>0){
            rows=strWidth/rowWidth+1;
        }else{
            rows=strWidth/rowWidth;
        }
        return rows;
    }

    public InputStream getResourceStream(String filePath) {
        return this.getClass().getResourceAsStream(filePath);
    }

    /**
     * 将bufferedImage 转成file
     *
     * @param bufferedImage
     * @return File
     * @throws Exception
     */
    public MultipartFile getFile(BufferedImage bufferedImage) throws Exception {
        //创建一个ByteArrayOutputStream
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        //把BufferedImage写入ByteArrayOutputStream
        ImageIO.write(bufferedImage, "png", os);
        //ByteArrayOutputStream转成InputStream
        InputStream input = new ByteArrayInputStream(os.toByteArray());
        //InputStream转成MultipartFile
        MultipartFile multipartFile = new MockMultipartFile("file", "file.png", "text/plain", input);
        return multipartFile;
    }


    /**
     * 生成二维码并转成图片
     *
     * @return
     */
    public MultipartFile createQrCode(String qrCodeContent) {
        // 生成二维码
        MultipartFile multipartFile = null;
        try {
            BufferedImage bufferedImage = QRCodeUtils.encode(qrCodeContent, false);
            //创建一个ByteArrayOutputStream
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            //把BufferedImage写入ByteArrayOutputStream
            ImageIO.write(bufferedImage, "jpg", os);
            InputStream input = new ByteArrayInputStream(os.toByteArray());
            multipartFile = new MockMultipartFile("file", "file.jpg", "text/plain", input);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return multipartFile;
    }

    public static void main(String[] args) {
        try {
            BufferedImage image = PosterUtils.createImage();
            ImageIO.write(image, "png", new File("D:\\demo101.png"));
            System.out.println("***********图片合成了********");

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
package com.example.demo.utils;

import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.OutputStream;
import java.util.Hashtable;
import java.util.Random;

/**
 * 二维码工具类
 * */
public class QRCodeUtils {

	private static final String CHARSET = "utf-8";
	private static final String FORMAT_NAME = "JPG";
	// 二维码尺寸
	private static final int QRCODE_SIZE = 900;
	// LOGO宽度
	private static final int WIDTH = 60;
	// LOGO高度
	private static final int HEIGHT = 60;

	private static BufferedImage createImage(String content, String imgPath,
											 boolean needCompress) throws Exception {
		Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
		hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
		hints.put(EncodeHintType.CHARACTER_SET, CHARSET);
		hints.put(EncodeHintType.MARGIN, 1);
		BitMatrix bitMatrix = new MultiFormatWriter().encode(content,
				BarcodeFormat.QR_CODE, QRCODE_SIZE, QRCODE_SIZE, hints);
		int width = bitMatrix.getWidth();
		int height = bitMatrix.getHeight();
		BufferedImage image = new BufferedImage(width, height,
				BufferedImage.TYPE_INT_RGB);

		for (int x = 0; x < width; x++) {
			for (int y = 0; y < height; y++) {
				image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000
						: 0xFFFFFFFF);
			}
		}

		if (imgPath == null || "".equals(imgPath)) {
			return image;
		}
		// 插入图片
		QRCodeUtils.insertImage(image, imgPath, needCompress);
		return image;
	}

	/**
	 * 插入LOGO
	 *
	 * @param source
	 *            二维码图片
	 * @param imgPath
	 *            LOGO图片地址
	 * @param needCompress
	 *            是否压缩
	 * @throws Exception
	 */
	private static void insertImage(BufferedImage source, String imgPath,
									boolean needCompress) throws Exception {
		File file = new File(imgPath);
		if (!file.exists()) {
			System.err.println(""+imgPath+"   该文件不存在!");
			return;
		}
		Image src = ImageIO.read(new File(imgPath));
		int width = src.getWidth(null);
		int height = src.getHeight(null);
		// 压缩LOGO
		if (needCompress) {
			if (width > WIDTH) {
				width = WIDTH;
			}
			if (height > HEIGHT) {
				height = HEIGHT;
			}
			Image image = src.getScaledInstance(width, height,
					Image.SCALE_SMOOTH);
			BufferedImage tag = new BufferedImage(width, height,
					BufferedImage.TYPE_INT_RGB);
			Graphics g = tag.getGraphics();
			// 绘制缩小后的图
			g.drawImage(image, 0, 0, null);
			g.dispose();
			src = image;
		}
		// 插入LOGO
		Graphics2D graph = source.createGraphics();
		int x = (QRCODE_SIZE - width) / 2;
		int y = (QRCODE_SIZE - height) / 2;
		graph.drawImage(src, x, y, width, height, null);
		Shape shape = new RoundRectangle2D.Float(x, y, width, width, 6, 6);
		graph.setStroke(new BasicStroke(3f));
		graph.draw(shape);
		graph.dispose();
	}

	/**
	 * 生成二维码(内嵌LOGO)
	 *
	 * @param content
	 *            内容
	 * @param imgPath
	 *            LOGO地址
	 * @param destPath
	 *            存放目录
	 * @param needCompress
	 *            是否压缩LOGO
	 * @throws Exception
	 */
	public static String encode(String content, String imgPath, String destPath,
								boolean needCompress) throws Exception {
		BufferedImage image = QRCodeUtils.createImage(content, imgPath,
				needCompress);
		mkdirs(destPath);
		String file = new Random().nextInt(99999999)+".jpg";
		ImageIO.write(image, FORMAT_NAME, new File(destPath+"/"+file));
		return file;
	}


	public static BufferedImage encode(String content,boolean needCompress) throws Exception {
		BufferedImage image = QRCodeUtils.createImage(content, null,
				needCompress);
		return image;
	}


	/**
	 * 当文件夹不存在时,mkdirs会自动创建多层目录,区别于mkdir.(mkdir如果父目录不存在则会抛出异常)
	 * @date 2013-12-11 上午10:16:36
	 * @param destPath 存放目录
	 */
	public static void mkdirs(String destPath) {
		File file =new File(destPath);
		//当文件夹不存在时,mkdirs会自动创建多层目录,区别于mkdir.(mkdir如果父目录不存在则会抛出异常)
		if (!file.exists() && !file.isDirectory()) {
			file.mkdirs();
		}
	}

	/**
	 * 生成二维码(内嵌LOGO)
	 *
	 * @param content
	 *            内容
	 * @param imgPath
	 *            LOGO地址
	 * @param destPath
	 *            存储地址
	 * @throws Exception
	 */
	public static void encode(String content, String imgPath, String destPath)
			throws Exception {
		QRCodeUtils.encode(content, imgPath, destPath, false);
	}

	/**
	 * 生成二维码
	 *
	 * @param content
	 *            内容
	 * @param destPath
	 *            存储地址
	 * @param needCompress
	 *            是否压缩LOGO
	 * @throws Exception
	 */
	public static void encode(String content, String destPath,
							  boolean needCompress) throws Exception {
		QRCodeUtils.encode(content, null, destPath, needCompress);
	}

	/**
	 * 生成二维码
	 *
	 * @param content
	 *            内容
	 * @param destPath
	 *            存储地址
	 * @throws Exception
	 */
	public static void encode(String content, String destPath) throws Exception {
		QRCodeUtils.encode(content, null, destPath, false);
	}

	/**
	 * 生成二维码(内嵌LOGO)
	 *
	 * @param content
	 *            内容
	 * @param imgPath
	 *            LOGO地址
	 * @param output
	 *            输出流
	 * @param needCompress
	 *            是否压缩LOGO
	 * @throws Exception
	 */
	public static void encode(String content, String imgPath,
							  OutputStream output, boolean needCompress) throws Exception {
		BufferedImage image = QRCodeUtils.createImage(content, imgPath,
				needCompress);
		ImageIO.write(image, FORMAT_NAME, output);
	}

	/**
	 * 生成二维码
	 *
	 * @param content
	 *            内容
	 * @param output
	 *            输出流
	 * @throws Exception
	 */
	public static void encode(String content, OutputStream output)
			throws Exception {
		QRCodeUtils.encode(content, null, output, false);
	}

	/**
	 * 解析二维码
	 *
	 * @param file
	 *            二维码图片
	 * @return
	 * @throws Exception
	 */
	public static String decode(File file) throws Exception {
		BufferedImage image;
		image = ImageIO.read(file);
		if (image == null) {
			return null;
		}
		BufferedImageLuminanceSource source = new BufferedImageLuminanceSource(
				image);
		BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
		Result result;
		Hashtable<DecodeHintType, Object> hints = new Hashtable<DecodeHintType, Object>();
		hints.put(DecodeHintType.CHARACTER_SET, CHARSET);
		result = new MultiFormatReader().decode(bitmap, hints);
		String resultStr = result.getText();
		return resultStr;
	}

	/**
	 * 解析二维码
	 *
	 * @param path
	 *            二维码图片地址
	 * @return
	 * @throws Exception
	 */
	public static String decode(String path) throws Exception {
		return QRCodeUtils.decode(new File(path));
	}

	private static BitMatrix deleteWhite(BitMatrix matrix) {
		int[] rec = matrix.getEnclosingRectangle();
		int resWidth = rec[2] + 1;
		int resHeight = rec[3] + 1;

		BitMatrix resMatrix = new BitMatrix(resWidth, resHeight);
		resMatrix.clear();
		for (int i = 0; i < resWidth; i++) {
			for (int j = 0; j < resHeight; j++) {
				if (matrix.get(i + rec[0], j + rec[1])){
					resMatrix.set(i, j);
				}
			}
		}
		return resMatrix;
	}

}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值