java图片转文本代码 java图片转字符

怎么样用Java实现将一张图片转成字符画??#首先在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; xbfedimage.getWidth(); x) {
for (int y = 0; ybfedimage.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; ycss[0].length; y) {
for (int x = 0; xcss.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");
}
public static String toHTML(String s) {
s = s.replaceAll("", "");
s = s.replaceAll(" ", " ");
【java图片转文本代码 java图片转字符】s = s.replaceAll("", "");
s = s.replaceAll("", "");
s = s.replaceAll("\"", """);
s = s.replaceAll("\\\r\\\n", "br/");
s = s.replaceAll("\\\r", "br/");
s = s.replaceAll("\\\n", "br/");
return s;
}
public static String replaceStrAllNotBack(String str, String strSrc, String strDes) {
StringBuffer sb = new StringBuffer(str);
int index = 0;
while ((index = sb.indexOf(strSrc, index)) != -1) {
sb.replace(index, indexstrSrc.length(), strDes);
index= strDes.length();
}
return sb.toString();
}
/**
* 读文件(使用默认编码)
*
* @param file
* @return 文件内容
* @throws IOException
*/
public static String readFile(File file, String charset) throws IOException {
InputStreamReader fr = new InputStreamReader(new FileInputStream(file), charset);
StringBuffer sb = new StringBuffer();
char[] bs = new char[1024];
int i = 0;
while ((i = fr.read(bs)) != -1) {
sb.append(bs, 0, i);
}
fr.close();
return sb.toString();
}
/**
* 写文件
*
* @param file
* @param string
*字符串
* @param encoding
*编码
* @return 文件大小
* @throws IOException
*/
public static int writeFile(File file, String string, String encoding) throws IOException {
FileOutputStream fos = new FileOutputStream(file);
try {
byte[] bs = string.getBytes(encoding);
fos.write(bs);
return bs.length;
} finally {
fos.close();
}
}
}
#打开"D:\content.html"文件看效果吧 。
有什么问题可以联系我 。
java图片转字符画你有几个地方错了
for (int y = 0; yimage.getHeight(); y= 8) {
for (int x = 0; ximage.getHeight(); x= 4) {
final int pixel = image.getRGB(x, y);
final int r = (pixel0xff0000)16, g = (pixel0xff00)8, b = pixel0xff;
final float gray = 0.299f * r0.578f * g0.114f * b;
final int index = Math.round(gray * (base.length()1) / 255);
System.out.println(index = base.length() ? " " : String.valueOf(base.charAt(index)));
}
System.out.println();
}
改为:
for (int y = 0; yimage.getHeight(); y= 8) {
for (int x = 0; ximage.getWidth(); x= 4) {
final int pixel = image.getRGB(x, y);
final int r = (pixel0xff0000)16, g = (pixel0xff00)8, b = pixel0xff;
final float gray = 0.299f * r0.578f * g0.114f * b;
final int index = Math.round(gray * (base.length()1) / 255);
System.out.print(index = base.length() ? " " : String.valueOf(base.charAt(index)));
}
System.out.println();
}
注意第二行使用image.getWidth(),第七行的println写成print,否则每个字符都会换行 。
[急急急急急急急急急急]JAVA程式编写一问(将图片转至ASCII)//1.jpg是原图,1.txt是转换后的文本,2.jpg是转换后的图像,图片宽度超过1024请用notepad查看转换后的文本哦
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileWriter;
import javax.imageio.ImageIO;
public class dd {
public static void main(String[] args) throws Exception {
char[][] result=imageToASCII(new File("D:/1.jpg"));
FileWriter fw=new FileWriter(new File("D:/1.txt"),true);
for (int i=0;iresult.length;i){
fw.write(result[i]);
}
fw.flush();
fw.close();
}
public static char[][] imageToASCII(File f) throws Exception{
BufferedImage img1 = ImageIO.read(f);
int h = img1.getHeight();
int w = img1.getWidth();
BufferedImage img2 = new BufferedImage(w,h,img1.getType());
char[][] gray = new char[h][w 2];
for (int x = 0; xh; x) {
for (int y = 0; yw; y) {
int argb = img1.getRGB(y, x);
int r = (argb16)0xFF;
int g = (argb8)0xFF;
int b = (argb0)0xFF;
int grayPixel = (int)(0.299*r 0.587*g 0.114*b);
if (grayPixel=230) gray[x][y]=' ';
else if (grayPixel=200) gray[x][y]='.';
else if (grayPixel=180) gray[x][y]='*';
else if (grayPixel=160) gray[x][y]=':';
else if (grayPixel=130) gray[x][y]='o';
else if (grayPixel=100) gray[x][y]='';
else if (grayPixel=70) gray[x][y]='8';
else if (grayPixel=50) gray[x][y]='#';
else gray[x][y]='@';
System.out.print(gray[x][y]);
img2.setRGB(y, x, (grayPixel16) (grayPixel8) grayPixel);
}
gray[x][w]='\r';gray[x][w 1]='\n';
System.out.println();
}
ImageIO.write(img2, "jpg", new File("D:/2.jpg"));
return gray;
}
}
关于通过java实现图片格式的转换import java.io.*; import java.awt.*; import java.awt.image.*;
import java.awt.Graphics; import java.awt.color.ColorSpace;
import javax.imageio.ImageIO;
public class ImageCut {
/**
* 缩放图像
* @param srcImageFile源图像文件地址
* @param result缩放后的图像地址
* @param scale缩放比例
* @param flag缩放选择:true 放大; false 缩小;
*/
public static void scale(String srcImageFile, String result, int scale,
boolean flag) {
try {
BufferedImage src = https://www.04ip.com/post/ImageIO.read(new File(srcImageFile)); // 读入文件
int width = src.getWidth(); // 得到源图宽
int height = src.getHeight(); // 得到源图长
if (flag) {// 放大
width = width * scale;
height = height * scale;
} else {// 缩小
width = width / scale;
height = height / scale;
}
Image image = src.getScaledInstance(width, height,
Image.SCALE_DEFAULT);
BufferedImage tag = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
Graphics g = tag.getGraphics();
g.drawImage(image, 0, 0, null); // 绘制缩小后的图
g.dispose();
ImageIO.write(tag, "JPEG", new File(result));// 输出到文件流
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 图像切割
* @param srcImageFile源图像地址
* @param descDir切片目标文件夹
* @param destWidth目标切片宽度
* @param destHeight目标切片高度
*/
public static void cut(String srcImageFile, String descDir, int destWidth,
int destHeight) {
try {
Image img;
ImageFilter cropFilter; // 读取源图像
BufferedImage bi = ImageIO.read(new File(srcImageFile));
int srcWidth = bi.getHeight(); // 源图宽度
int srcHeight = bi.getWidth(); // 源图高度
if (srcWidthdestWidthsrcHeightdestHeight) {
Image image = bi.getScaledInstance(srcWidth, srcHeight,
Image.SCALE_DEFAULT);
destWidth = 200; // 切片宽度
destHeight = 150; // 切片高度
int cols = 0; // 切片横向数量
int rows = 0; // 切片纵向数量
// 计算切片的横向和纵向数量
if (srcWidth % destWidth == 0) {
cols = srcWidth / destWidth;
} else {
cols = (int) Math.floor(srcWidth / destWidth)1;
}
if (srcHeight % destHeight == 0) {
rows = srcHeight / destHeight;
} else {
rows = (int) Math.floor(srcHeight / destHeight)1;
}
// 循环建立切片
// 改进的想法:是否可用多线程加快切割速度
for (int i = 0; irows; i) {
for (int j = 0; jcols; j) {
// 四个参数分别为图像起点坐标和宽高
// 即: CropImageFilter(int x,int y,int width,int height)
cropFilter = new CropImageFilter(j * 200, i * 150,
destWidth, destHeight);
img = Toolkit.getDefaultToolkit().createImage(
new FilteredImageSource(image.getSource(),
cropFilter));
BufferedImage tag = new BufferedImage(destWidth,
destHeight, BufferedImage.TYPE_INT_RGB);
Graphics g = tag.getGraphics();
g.drawImage(img, 0, 0, null); // 绘制缩小后的图
g.dispose();
// 输出为文件
ImageIO.write(tag, "JPEG", new File(descDir
"pre_map_"i"_"j".jpg"));
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
// 图像类型转换GIF-JPG GIF-PNG PNG-JPG PNG-GIF(X)
public static void convert(String source, String result) {
try {
File f = new File(source);
f.canRead();
f.canWrite();
BufferedImage src = https://www.04ip.com/post/ImageIO.read(f);
ImageIO.write(src, "JPG", new File(result));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// 彩色转为黑白
public static void gray(String source, String result) {
try {
BufferedImage src = https://www.04ip.com/post/ImageIO.read(new File(source));
ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_GRAY);
ColorConvertOp op = new ColorConvertOp(cs, null);
src = https://www.04ip.com/post/op.filter(src, null);
ImageIO.write(src, "JPEG", new File(result));
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
//cut("e:/1.jpg", "e:/t/", 200, 150);
}
}
import java.io.*; import java.awt.*; import java.awt.image.*;
import java.awt.Graphics; import java.awt.color.ColorSpace;
import javax.imageio.ImageIO;
public class ImageCut {
/**
* 缩放图像
* @param srcImageFile源图像文件地址
* @param result缩放后的图像地址
* @param scale缩放比例
* @param flag缩放选择:true 放大; false 缩小;
*/
public static void scale(String srcImageFile, String result, int scale,
boolean flag) {
try {
BufferedImage src = https://www.04ip.com/post/ImageIO.read(new File(srcImageFile)); // 读入文件
int width = src.getWidth(); // 得到源图宽
int height = src.getHeight(); // 得到源图长
if (flag) {// 放大
width = width * scale;
height = height * scale;
} else {// 缩小
width = width / scale;
height = height / scale;
}
Image image = src.getScaledInstance(width, height,
Image.SCALE_DEFAULT);
BufferedImage tag = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
Graphics g = tag.getGraphics();
g.drawImage(image, 0, 0, null); // 绘制缩小后的图
g.dispose();
ImageIO.write(tag, "JPEG", new File(result));// 输出到文件流
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 图像切割
* @param srcImageFile源图像地址
* @param descDir切片目标文件夹
* @param destWidth目标切片宽度
* @param destHeight目标切片高度
*/
public static void cut(String srcImageFile, String descDir, int destWidth,
int destHeight) {
try {
Image img;
ImageFilter cropFilter; // 读取源图像
BufferedImage bi = ImageIO.read(new File(srcImageFile));
int srcWidth = bi.getHeight(); // 源图宽度
int srcHeight = bi.getWidth(); // 源图高度
if (srcWidthdestWidthsrcHeightdestHeight) {
Image image = bi.getScaledInstance(srcWidth, srcHeight,
Image.SCALE_DEFAULT);
destWidth = 200; // 切片宽度
destHeight = 150; // 切片高度
int cols = 0; // 切片横向数量
int rows = 0; // 切片纵向数量
// 计算切片的横向和纵向数量
if (srcWidth % destWidth == 0) {
cols = srcWidth / destWidth;
} else {
cols = (int) Math.floor(srcWidth / destWidth)1;
}
if (srcHeight % destHeight == 0) {
rows = srcHeight / destHeight;
} else {
rows = (int) Math.floor(srcHeight / destHeight)1;
}
// 循环建立切片
// 改进的想法:是否可用多线程加快切割速度
for (int i = 0; irows; i) {
for (int j = 0; jcols; j) {
// 四个参数分别为图像起点坐标和宽高
// 即: CropImageFilter(int x,int y,int width,int height)
cropFilter = new CropImageFilter(j * 200, i * 150,
destWidth, destHeight);
img = Toolkit.getDefaultToolkit().createImage(
new FilteredImageSource(image.getSource(),
cropFilter));
BufferedImage tag = new BufferedImage(destWidth,
destHeight, BufferedImage.TYPE_INT_RGB);
Graphics g = tag.getGraphics();
g.drawImage(img, 0, 0, null); // 绘制缩小后的图
g.dispose();
// 输出为文件
ImageIO.write(tag, "JPEG", new File(descDir
"pre_map_"i"_"j".jpg"));
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
// 图像类型转换GIF-JPG GIF-PNG PNG-JPG PNG-GIF(X)
public static void convert(String source, String result) {
try {
File f = new File(source);
f.canRead();
f.canWrite();
BufferedImage src = https://www.04ip.com/post/ImageIO.read(f);
ImageIO.write(src, "JPG", new File(result));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// 彩色转为黑白
public static void gray(String source, String result) {
try {
BufferedImage src = https://www.04ip.com/post/ImageIO.read(new File(source));
ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_GRAY);
ColorConvertOp op = new ColorConvertOp(cs, null);
src = https://www.04ip.com/post/op.filter(src, null);
ImageIO.write(src, "JPEG", new File(result));
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
//cut("e:/1.jpg", "e:/t/", 200, 150);
}
}
参考文献:
关于java图片转文本代码和java图片转字符的介绍到此就结束了,不知道你从中找到你需要的信息了吗 ?如果你还想了解更多这方面的信息,记得收藏关注本站 。

    推荐阅读