java 生成banner

import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.font.FontRenderContext;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.IOException;

public class BannerTest {
 
	public static void main(String[] args) throws IOException {
		FontRenderContext context = new FontRenderContext(new AffineTransform(), false, false);
		/**
		 * Font.PLAIN(普通)
		 * Font.BOLD(加粗)
		 * Font.ITALIC(斜体)
		 * Font.BOLD+ Font.ITALIC(粗斜体)
		 */
		Font font = new Font("微软雅黑", Font.PLAIN, 24);
        String content = " 你 好 java";
        double width = font.getStringBounds(content, context).getWidth();//计算图片的宽
        double height = font.getStringBounds(content, context).getHeight();//计算高c
        int minx=(int)width;
        int miny=(int)(height*1.5);
        BufferedImage bufferedImage = new BufferedImage(minx, miny, BufferedImage.TYPE_INT_RGB);
        Graphics2D graphics = bufferedImage.createGraphics();
        graphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
        graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));
        //设置背影为白色
        graphics.setColor(Color.WHITE);
        graphics.fillRect(0, 0, bufferedImage.getWidth(), bufferedImage.getHeight());
        graphics.setFont(font);
        graphics.setColor(Color.BLACK);
        graphics.drawString(content, 0, (int)height);//图片上写文字
        graphics.dispose();
        StringBuffer sb=new StringBuffer();
        for (int i = 0; i < miny; i++) {
        	for (int j = 0; j < minx; j++) {
        		int rgb=bufferedImage.getRGB(j, i);
        		if(rgb!=-1) {
        			sb.append((int)(Math.random()*(9+1)));
        		}else {
        			sb.append(" ");
        		}
    		}
        	sb.append("\n");
		}
        System.out.println(sb.toString());
	}

}

测试结果:
在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值