java图片转文本代码 java 图片转字符串
[急急急急急急急急急急]JAVA程式编写一问(将图片转至ASCII)
//1.jpg是原图,1.txt是转换后的文本,2.jpg是转换后的图像,图片宽度超过1024请用notepad++查看转换后的文本哦
成都创新互联公司从2013年成立,先为唐县等服务建站,唐县等地企业,进行企业商务咨询服务。为唐县企业网站制作PC+手机+微官网三网同步一站式服务解决您的所有建站问题。
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; x h; x++) {
for (int y = 0; y w; y++) {
int argb = img1.getRGB(y, x);
int r = (argb 16) 0xFF;
int g = (argb 8) 0xFF;
int b = (argb 0) 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实现将一张图片转成字符画??
#首先在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");
}
public static String toHTML(String s) {
s = s.replaceAll("", "");
s = s.replaceAll(" ", " ");
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, index + strSrc.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实现图片格式的转换
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 = 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 (srcWidth destWidth srcHeight destHeight) {
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; i rows; i++) {
for (int j = 0; j cols; 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 = 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 = ImageIO.read(new File(source));
ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_GRAY);
ColorConvertOp op = new ColorConvertOp(cs, null);
src = 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 = 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 (srcWidth destWidth srcHeight destHeight) {
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; i rows; i++) {
for (int j = 0; j cols; 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 = 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 = ImageIO.read(new File(source));
ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_GRAY);
ColorConvertOp op = new ColorConvertOp(cs, null);
src = 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 图片转字符串
网页URL:http://myzitong.com/article/dddsdgp.html