Java实验任务:
编写一个 Java 程序,将图片中的相关像素读取之后,用字符表示,把整张图片转换成字符画的形式,存储在一个纯文本文件里面
任务:
编写一个 Java 程序,将图片中的相关像素读取之后,用字符表示,把整张图片转换成字符画的形式,存储在一个纯文本文件里面,实现效果如下图:
(别说有点好看+可爱 (●’◡’●) 😊
发现个好看的
再 + 一张实现效果图:
ps:先看个好笑的😀(因为用记事本打开字体没选对,它就变异了😂
(在生成字符画的时候,用记事本打开,默认的字体会影响出来的实际效果,如微软雅黑字体有如上效果)
原因:因为微软雅黑字体的一些字符大小有的不太一样,所以出来会有点奇怪,
解决方案:只需在记事本中在编辑处将字体改为宋体,就可以正常显示了 (☆▽☆)
实现的详细代码:
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
public class shiyan3_3 {
public static void main(String []args){
// 输入保存的txt文件路径
String txtPath = "D:/Users/1.txt";
// 输入准备转换的图片路径
String imagePath = "D:/Users/xxx/xxx/xxx.jpg";
new ImageConvertTool(imagePath,txtPath);
}
}
class ImageConvertTool {
private static String imagePath, txtPath;
private static int imageHeight, imageWidth;
private static String replaceString = "$@B%8&WM#*oahkbmZO0QJUYXzcvunxrjft/|()1{}[]?-_+~<>i!lI;:,^`'. ";
private static StringBuffer imageString = new StringBuffer();
public ImageConvertTool(String imagePath, String txtPath) {
this.imagePath = imagePath;
this.txtPath = txtPath;
imageProcess();
imageSave();
}
private static void imageProcess() {
try {
BufferedImage image = ImageIO.read(new File(imagePath));
imageHeight = image.getHeight();
imageWidth = image.getWidth();
for (int height = 0; height < imageHeight; height += 2) {
for (int width = 0; width < imageWidth; width++) {
// 像素点RBG值获取
int pixel = image.getRGB(width, height);
int R = (pixel & 0xff0000) >> 16;
int B = pixel & 0xff;
int G = (pixel & 0xff00) >> 8;
// 灰度计算公式
float pixelGray = 0.299f * R + 0.587f * G + 0.114f * B;
int pixelIndex = Math.round(pixelGray * (replaceString.length() + 1) / 255);
// 将灰度值转成字符
String pixelChar = pixelIndex >= replaceString.length() ? " " : String.valueOf(replaceString.charAt(pixelIndex));
// 控制台上输出
System.out.print(pixelChar);
// 添加到imageString中
imageString.append(pixelChar);
}
System.out.println();
imageString.append('\n');
}
} catch (IOException error) {
error.printStackTrace();
}
}
private static void imageSave() {
File file = new File(txtPath);
if (!file.exists())
try {
file.createNewFile();
} catch (Exception error) {
error.printStackTrace();
}
try {
FileWriter fileWriter = new FileWriter(file);
String temp = new String(imageString);
fileWriter.write(temp);
fileWriter.close();
} catch (Exception error) {
error.printStackTrace();
}
}
}
设计思路:
- 读取图片:使用ImageIO类的read方法读取指定路径的图片文件,获取图片的像素矩阵。
- 灰度化处理:遍历图片的像素矩阵,对每个像素的RGB值进行加权平均,得到对应的灰度值。
- 字符映射:根据灰度值将像素映射到指定的字符上,例如将灰度值映射到字符串"@#8XOHLTI)i=+;:,. "上,灰度值越高,对应的字符越简单。
- 输出到文本文件:将映射后的字符逐行输出到文本文件中,形成字符画。
哈哈感觉这个图片转字符还挺有意思的,祝大家实验作业都顺顺利利,和和美美结束!!Over!