欢迎您访问365答案网,请分享给你的朋友!
生活常识 学习资料

java代码生成春节对联

时间:2023-08-09
使用java代码,生成春节对联

先上代码:

import sun.font.FontDesignMetrics;import javax.imageio.ImageIO;import java.awt.*;import java.awt.image.BufferedImage;import java.io.*;public class chunlian { //设置生成文件存放文件夹 final static String imageFolderPath = "D://chunlian//1"; //设置背景图 final static String sourceFilePath = "D://chunlian//11.png"; //设置字体 final static String fontName = "宋体"; public static void main(String[] args) { write(); } public static void write(){ BufferedImage image = new BufferedImage(640*4, 640+2*640*7, BufferedImage.TYPE_INT_RGB); Graphics g = image.createGraphics(); g.drawImage(writeH("恭喜发财"),0,0,640*4,640,null); g.drawImage(writeV("三江进宝百业旺"),0,640,640*2,2*640*7,null); g.drawImage(writeV("四海来财万福春"),2*640,640,640*2,2*640*7,null); //输出文件 try { ImageIO.write(image,"png",new File(imageFolderPath +"春联.png")); } catch (IOException e) { e.printStackTrace(); } } public static BufferedImage writeH(String text){ char[] ch= text.toCharArray(); BufferedImage image = new BufferedImage(640*ch.length, 640, BufferedImage.TYPE_INT_RGB); Graphics g = image.createGraphics(); for (int i = 0; i < ch.length; i++) { char c = ch[i]; g.drawImage(fontMark(String.valueOf(c)),640*i,0,640,640,null); } g.dispose(); return image; } public static BufferedImage writeV(String text){ char[] ch= text.toCharArray(); BufferedImage image = new BufferedImage(2*640, 2*640*ch.length, BufferedImage.TYPE_INT_RGB); Graphics g = image.createGraphics(); for (int i = 0; i < ch.length; i++) { char c = ch[i]; g.drawImage(fontMark(String.valueOf(c)),0,2*640*i,2*640,2*640,null); } g.dispose(); return image; } public static BufferedImage fontMark(String content) { try { BufferedImage image = ImageIO.read(new File(sourceFilePath)); return fontMark(image, content); } catch (IOException e) { return null; } } //文字标记 public static BufferedImage fontMark(BufferedImage bufImg, String content) { Font font = new Font(fontName, Font.BOLD, 400); FontDesignMetrics metrics = FontDesignMetrics.getMetrics(font); Graphics2D graphics = bufImg.createGraphics(); graphics.setColor(Color.black); graphics.setFont(font); graphics.drawString(content, 120, 460); graphics.dispose(); System.out.println(content); return bufImg; }}

然后设置图片

运行即可,如果sun.font运行出现问题,显示:程序包 sun.font 已在模块 java.desktop 中声明, 但该模块未导出它,请参考https://blog.csdn.net/weixin_45721386/article/details/122782192?spm=1001.2014.3001.5501

运行截图:

Copyright © 2016-2020 www.365daan.com All Rights Reserved. 365答案网 版权所有 备案号:

部分内容来自互联网,版权归原作者所有,如有冒犯请联系我们,我们将在三个工作时内妥善处理。