Last active
June 24, 2019 06:29
-
-
Save TouiSoraHe/758bf48fe26902f13676ff84ebc582a8 to your computer and use it in GitHub Desktop.
图片转字符画
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.awt.image.BufferedImage; | |
import java.io.BufferedWriter; | |
import java.io.File; | |
import java.io.FileWriter; | |
import java.io.IOException; | |
import javax.imageio.ImageIO; | |
//可以将图片转换为字符画 | |
public class ImgToChar { | |
static String charList = new String("$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\\|()1{}[]?-_+~<>i!lI;:,\"^`'. "); | |
static String imgPath = "input";//图片的路径 | |
static String outputName = "output.txt";//输出TXT文件的路径 | |
public static void main(String[] args) throws IOException { | |
BufferedImage image= ImageIO.read(new File(imgPath)); | |
File writename = new File(outputName); | |
writename.createNewFile(); | |
BufferedWriter out = new BufferedWriter(new FileWriter(writename)); | |
int density = 4; | |
for(int y = 0;y<image.getHeight();++y) | |
{ | |
if((y%density )!=0) | |
continue; | |
for(int x =0 ;x<image.getWidth();++x) | |
{ | |
if((x%density )!=0) | |
continue; | |
int RGB = image.getRGB(x, y); | |
int a = (RGB>>24) & 255; | |
int r = (RGB>>16) & 255; | |
int g = (RGB>>8) & 255; | |
int b = RGB & 255; | |
char c = getChar(r,g,b,a); | |
out.write(c); | |
out.write(c); | |
} | |
out.newLine(); | |
} | |
out.flush(); | |
out.close(); | |
} | |
static char getChar(int r,int g,int b,int a) | |
{ | |
if(a==0) | |
return ' '; | |
int gray = (int) (0.2126 * r + 0.7152 * g + 0.0722 * b); | |
double unti = 256.0/charList.length(); | |
int index = (int) (gray/unti); | |
return charList.charAt(index); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment