原圖

生成字符畫文本(像素轉換字符顯示后,打開字符畫顯示相當于原圖的好幾倍大,不要用記事本打開,建議用notepad++等軟體打開)

生成字符畫圖片(背景顏色和畫筆顏色代碼里可設定調節)

新建普通java 專案,Java單類實作代碼,復制到java專案中,用idea編輯器 主方法運行,(引入的Class 都是JDK中自有的)
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
public class ImageToASCII {
//三十二位顏色
private final static char[] color = {' ', '`', '.', '^', ',', ':', '~', '"',
'<', '!', 'c', 't', '+', '{', 'i', '7', '?', 'u', '3', '0', 'p', 'w',
'4', 'A', '8', 'D', 'X', '%', '#', 'H', 'W', 'M'};
/**
* 圖片轉字符畫文本
*/
public static void createCharTxt(String path, String fileUrl) {
try {
BufferedImage image = ImageIO.read(new File(path));
StringBuilder imageToAscii = imageToAscii(image);
FileWriter fileWriter = new FileWriter(fileUrl);
fileWriter.write(imageToAscii.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 圖片轉字符
*/
public static StringBuilder imageToAscii(BufferedImage image) {
StringBuilder sb = new StringBuilder();
int width = image.getWidth();
int height = image.getHeight();
for (int y = 0; y < height; y++) {
for (int x= 0; x < width; x++) {
sb.append(rgbToChar(image,x,y)+ " ");
}
sb.append("\n");
}
return sb;
}
/**
* 像素轉位元組
*/
public static char rgbToChar(BufferedImage image,int x,int y){
int rgb = image.getRGB(x, y);
int R = (rgb & 0xff0000) >> 16;
int G = (rgb & 0x00ff00) >> 8;
int B = rgb & 0x0000ff;
int gray = (R * 30 + G * 59 + B * 11 + 50) / 100;
int index = 31 * gray / 255;
return color[index];
}
/**
* @Description: 生成字符碼圖片
* @param imgPath 圖片路徑
* @param fileUrl 輸出圖片路徑
* @param more 放大倍數
* @throws
*/
public static void createCharImg(String imgPath, String fileUrl,int more){
try {
FileInputStream fileInputStream = new FileInputStream(imgPath);
BufferedImage image = ImageIO.read(fileInputStream);
//生成字符圖片
int w = image.getWidth();
int h = image.getHeight();
BufferedImage imageBuffer = new BufferedImage(w*more, h*more, 1);;
Graphics g = imageBuffer.getGraphics();
//設定背景色
g.setColor(Color.white);// 畫筆顏色
g.fillRect(0, 0, w*more, h*more);// 填充圖形背景
// 設定字體
g.setFont(new Font("宋體", Font.ITALIC, more)); //more*2:字體高度
g.setColor(Color.black);// 畫筆顏色
// 繪制字符
for (int y = 0; y < h; y++) {
for (int x = 0; x< w; x++) {
g.drawString(rgbToChar(image,x,y)+ " ", x*more, (y+1)*more); //繪制每行字體位置,主要y軸改變
}
}
g.dispose();
ImageIO.write(imageBuffer, "jpg", new File(fileUrl)); //輸出圖片
System.out.println("字符畫圖片生成");
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* @Description: 生成字符碼圖片
* @param imgPath 圖片路徑
* @param fileUrl 輸出圖片路徑
* @more 放大倍數
*/
public static void createCharImg(String imgPath, String fileUrl){
createCharImg(imgPath,fileUrl,1);
}
public static void main(String[] args) throws IOException {
createCharImg("C:\\Users\\tarzan\\Desktop\\home.jpg","C:\\Users\\tarzan\\Desktop\\a.jpg");
createCharTxt("C:\\Users\\tarzan\\Desktop\\home.jpg","C:\\Users\\tarzan\\Desktop\\a.txt");
}
}
運行結果截圖


更多推薦
《震驚,java僅用30行代碼就實作了視頻轉音頻的批量轉換》
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/279576.html
標籤:java
