图片转字符代码
JAVA代码
package te;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class T {
public static void createTxt(final String path) {
final String base = "@#&$%*o!;.";// 字符串由复杂到简单
FileOutputStream fop = null;
OutputStreamWriter streaWriter = null;
try {
String fiNa = path.substring(0, path.lastIndexOf("."));
File f = new File(fiNa+"a.txt");
fop = new FileOutputStream(f);
// 构建FileOutputStream对象,文件不存在会自动新建
streaWriter = new OutputStreamWriter(fop, "UTF-8");
// 构建OutputStreamWriter对象,参数可以指定编码,默认为操作系统默认编码,windows上是gbk
//换行
final BufferedImage image = ImageIO.read(new File(path));
for (int y = 0; y < image.getHeight(); y += 2) {
for (int x = 0; x < image.getWidth(); x++) {
final int pixel = image.getRGB(x, y);
final int r = (pixel & 0xff0000) >> 16, g = (pixel & 0xff00) >> 8, b = pixel & 0xff;
final float gray = 0.299f * r + 0.578f * g + 0.114f * b;
final int index = Math.round(gray * (base.length() + 1) / 255);
streaWriter.append(index >= base.length() ? " " : String.valueOf(base.charAt(index)));
}
streaWriter.append("\r\n");
}
} catch (final IOException e) {
e.printStackTrace();
}finally{
try {
streaWriter.close();
//关闭写入流,同时会把缓冲区内容写入文件,所以上面的注释掉
fop.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void main(final String[] args) {
T.createAsciiPic("F:\\HT\\liyings.jpg");
}
}
C#代码
class Program
{
static string strbase = "@#&$%*o!;.";// 字符串由复杂到简单
public static void createTxt(String path)
{
StreamWriter sw = null;
try
{
String fiNa = path.Substring(0, path.LastIndexOf("."));
sw = new StreamWriter(fiNa + "c.txt");
Bitmap image = new Bitmap(path);
for (int y = 0; y < image.Height; y += 2)
{
for (int x = 0; x < image.Width; x++)
{
Color myColor = new Color();
myColor = image.GetPixel(x, y);
//int r = (pixel & 0xff0000) >> 16, g = (pixel & 0xff00) >> 8, b = pixel & 0xff;
//float gray = 0.299f * r + 0.578f * g + 0.114f * b;
float gray = 0.299f * myColor.R + 0.578f * myColor.G + 0.114f * myColor.B;
int index = Convert.ToInt32(Math.Round(gray * (strbase.Length + 1) / 255));
sw.Write(index >= strbase.Length ? " " : strbase[index].ToString());
}
sw.WriteLine();
}
}
catch (IOException e)
{
}
finally
{
sw.Close();
}
}
static void Main(String[] args)
{
Program.createTxt("F:\\HT\\img\\lige.jpg");
}
}