日期:2014-05-20 浏览次数:20835 次
#首先在D盘写一个文件"temp.html",如下内容
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>图片转文本</title>
<meta http-equiv="content-type" content="text/html; charset=gbk">
<style type="text/css">
body {
font-family: 宋体; line-height: 0.8em; letter-spacing: 0px; font-size: 8px;
}
</style>
</head>
<body>
${content}
</body>
</html>
#在D盘放一个图片(放小一点的)"a.jpg"
#运行如下JAVA代码:
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import javax.imageio.ImageIO;
public class Test {
/** 此处设置灰度字符,此处只用十个字符,可以设置更多 */
private static char[] cs = new char[] { '.', ',', '*', '+', '=', '&', '$', '@', '#', ' ' };
public static void main(String[] args) throws IOException {
// 读取图片
BufferedImage bfedimage = ImageIO.read(new File("D:\\a.jpg"));
// 图片转字符串后的数组
char[][] css = new char[bfedimage.getWidth()][bfedimage.getHeight()];
for (int x = 0; x < bfedimage.getWidth(); x++) {
for (int y = 0; y < bfedimage.getHeight(); y++) {
int rgb = bfedimage.getRGB(x, y);
Color c = new Color(rgb);
// 得到灰度值
int cc = (c.getRed() + c.getGreen() + c.getBlue()) / 3;
css[x][y] = cs[(int) ((cc * 10 - 1) / 255)];
}
}
// 取得模板HTML
String temp = readFile(new File("D:\\temp.html"),"gbk");
StringBuffer sb = new StringBuffer();
// 开始拼接内容
for (int y = 0; y < css[0].length; y++) {
for (int x = 0; x < css.length; x++) {
sb.append(css[x][y]);
}
sb.append("\r\n");
}
System.out.println(sb.toString());
// 生成文件
String content = toHTML(sb.toString());
String filecontent = replaceStrAllNotBack(temp, "${content}", content);
writeFile(new File("D:\\content.html"), filecontent, "gbk");