用Java代码实现一幅春联详解
作者:Hi-Sunshine
大家好,本篇文章主要讲的是用Java代码实现一幅春联详解,感兴趣的同学赶快来看一看吧,对你有帮助的话记得收藏一下,方便下次浏览
快过年了,闲来无事,那就用自己的专业发挥一下作用吧。接下来我们就用java代码写一幅春联呗。具体代码如下:
模板图片如下:
package com.zmh.daily.spring; import javax.imageio.ImageIO; import java.awt.*; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; /** * 春联 * * @version v1.0 * @Author: sunshinezhang * @Date: 2022/1/25 3:27 下午 */ public class Couplet { //设置生成文件存放文件夹 final static String imageFolderPath = "/Users/sunshinezhang/Desktop/1/"; //设置背景图 final static String sourceFilePath = "/Users/sunshinezhang/Desktop/1/2.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, 350); Graphics2D graphics = bufImg.createGraphics(); graphics.setColor(Color.black); graphics.setFont(font); graphics.drawString(content, 230, 540); graphics.dispose(); System.out.println(content); return bufImg; } }
运行main方法以后,效果图如下:
到此这篇关于用Java代码实现一幅春联详解的文章就介绍到这了,更多相关Java春联内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!