已经临近一年没有发文了,年关了,闲了点,就没事瞎折腾,最近在 抖音 上看到一张猫的图片,是利用字符组成的猫的图片,听说挺火的,说是什么隐藏表白图片
想到干脆自己写个方法,用女朋友照片生成一张字符图,拿去做惊喜不是美滋滋,说干就干,代码走起
public static void toFontImage(String path,String base) {
//字体大小
int size = 11;
try {
//获取图片缓存区
BufferedImage bufferedImage = ImageIO.read(Paths.get(path).toFile());
//读取图片尺寸
int w = bufferedImage.getWidth();
int h = bufferedImage.getHeight();
int minW = bufferedImage.getMinX();
int minH = bufferedImage.getMinY();
BufferedImage outImage = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
//画笔
Graphics2D graphics2D = outImage.createGraphics();
graphics2D.setColor(null);
//填充
graphics2D.fillRect(0, 0, w, h);
//字符循环
int strIndex = 0;
//循环写入
for (int j = minH; j < h; j = j + size) {
for (int i = minW; i < w; i = i + size) {
int pixel = bufferedImage.getRGB(i, j);
graphics2D.setColor(new Color(pixel));
graphics2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
graphics2D.setFont(new Font("微软雅黑", Font.PLAIN, size));
graphics2D.drawString(String.valueOf(base.charAt(strIndex)), i, j);
if (strIndex >= base.length() - 1) {
strIndex = 0;
} else {
strIndex++;
}
}
}
graphics2D.dispose();
ImageIO.write(outImage, " jpg ", new FileOutputStream("F:/out.jpg"));
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws Exception {
toFontImage("f:/w.jpg","我好喜欢你啊");
}
代码不多,技术不难,就是个想法,折腾下,来看看效果图先
当然,这个效果可能还不太明显,字体大小有待调整优化,主要是 java 绘字体,尤其是小字体,总是会糊掉,如果大家有什么优化意见欢迎在下方留言!后面可以用这个生成一个gif图片也行,我记得当年b站很火的烂苹果,就有用java控制台打印的,不知道java能不能利用字符生成类似视频,这个有待研究!