import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
public 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();
}
}
}
public class Main {
public static void main(String []args){
// 输入保存的txt文件路径
String txtPath = "cat.txt";
// 输入准备转换的图片路径
String imagePath = "cat.jpg";
new ImageConvertTool(imagePath,txtPath);
}
}
标签:txtPath,imagePath,java,String,int,jpg,static,new,txt
From: https://blog.csdn.net/laocooon/article/details/140102955