//1.jpg是原圖,1.txt是轉(zhuǎn)換后的文本,2.jpg是轉(zhuǎn)換后的圖像,圖片寬度超過(guò)1024請(qǐng)用notepad++查看轉(zhuǎn)換后的文本哦
成都創(chuàng)新互聯(lián)公司從2013年成立,先為唐縣等服務(wù)建站,唐縣等地企業(yè),進(jìn)行企業(yè)商務(wù)咨詢服務(wù)。為唐縣企業(yè)網(wǎng)站制作PC+手機(jī)+微官網(wǎng)三網(wǎng)同步一站式服務(wù)解決您的所有建站問題。
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;
}
}
#首先在D盤寫一個(gè)文件"temp.html",如下內(nèi)容
!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
html
head
title圖片轉(zhuǎn)文本/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盤放一個(gè)圖片(放小一點(diǎn)的)"a.jpg"
#運(yùn)行如下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 {
/** 此處設(shè)置灰度字符,此處只用十個(gè)字符,可以設(shè)置更多 */
private static char[] cs = new char[] { '.', ',', '*', '+', '=', '', '$', '@', '#', ' ' };
public static void main(String[] args) throws IOException {
// 讀取圖片
BufferedImage bfedimage = ImageIO.read(new File("D:\\a.jpg"));
// 圖片轉(zhuǎn)字符串后的數(shù)組
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();
// 開始拼接內(nèi)容
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();
}
/**
* 讀文件(使用默認(rèn)編碼)
*
* @param file
* @return 文件內(nèi)容
* @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"文件看效果吧。
有什么問題可以聯(lián)系我。
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(); // 得到源圖長(zhǎng)
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切片目標(biāo)文件夾
* @param destWidth目標(biāo)切片寬度
* @param destHeight目標(biāo)切片高度
*/
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; // 切片橫向數(shù)量
int rows = 0; // 切片縱向數(shù)量
// 計(jì)算切片的橫向和縱向數(shù)量
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;
}
// 循環(huán)建立切片
// 改進(jìn)的想法:是否可用多線程加快切割速度
for (int i = 0; i rows; i++) {
for (int j = 0; j cols; j++) {
// 四個(gè)參數(shù)分別為圖像起點(diǎn)坐標(biāo)和寬高
// 即: 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();
}
}
// 圖像類型轉(zhuǎn)換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();
}
}
// 彩色轉(zhuǎn)為黑白
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(); // 得到源圖長(zhǎng)
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切片目標(biāo)文件夾
* @param destWidth目標(biāo)切片寬度
* @param destHeight目標(biāo)切片高度
*/
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; // 切片橫向數(shù)量
int rows = 0; // 切片縱向數(shù)量
// 計(jì)算切片的橫向和縱向數(shù)量
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;
}
// 循環(huán)建立切片
// 改進(jìn)的想法:是否可用多線程加快切割速度
for (int i = 0; i rows; i++) {
for (int j = 0; j cols; j++) {
// 四個(gè)參數(shù)分別為圖像起點(diǎn)坐標(biāo)和寬高
// 即: 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();
}
}
// 圖像類型轉(zhuǎn)換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();
}
}
// 彩色轉(zhuǎn)為黑白
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);
}
}
參考文獻(xiàn):
當(dāng)前標(biāo)題:java圖片轉(zhuǎn)文本代碼 java 圖片轉(zhuǎn)字符串
標(biāo)題鏈接:http://www.chinadenli.net/article18/dddsdgp.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供標(biāo)簽優(yōu)化、外貿(mào)網(wǎng)站建設(shè)、網(wǎng)站制作、網(wǎng)站維護(hù)、自適應(yīng)網(wǎng)站、全網(wǎng)營(yíng)銷推廣
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)