java实现图像转码为字符画的方法
程序员文章站
2023-11-29 15:41:16
本文实例为大家分享了java实现图像转码为字符画的具体代码,供大家参考,具体内容如下
public class imageprocesser {
p...
本文实例为大家分享了java实现图像转码为字符画的具体代码,供大家参考,具体内容如下
public class imageprocesser { private static final char[] charset1 = {'m','8','v','|',':','.',' '}; //默认字符素材集 private char[] charset; //字符画素材集 private string imgstring = ""; //储存转化后的字符串 //使用指定字符集构造 public imageprocesser(char[] charset){ this.charset = charset; } //使用默认字符集构造 public imageprocesser(){ this.charset = charset1; } public string getimgstring(){ return imgstring; } /*将图形文件转化为字符画字符串*/ public imageprocesser tobitmapconvert(string imagepath){ return tobitmapconvert(new file(imagepath)); } public imageprocesser tobitmapconvert(file imagefile){ stringbuffer sb = new stringbuffer(); if(!imagefile.exists()){ //当读取的文件不存在时,结束程序 system.out.println("file is not exists!"); system.exit(1); } color color; try{ bufferedimage buff = imageio.read(imagefile); //将图片文件装载如bufferedimage流 buff = compressimage(buff); int bitmaph = buff.getheight(); int bitmapw = buff.getwidth(); //逐行扫描图像的像素点,读取rgb值,取其平均值,并从charset中获取相应的字符素材,并装载到sb中 for(int y=0; y<bitmaph; y++){ for(int x=0; x<bitmapw; x++){ int rgb = buff.getrgb(x,y); color = new color(rgb); int cvalue = (color.getred()+color.getgreen()+color.getblue()) / 3; sb.append(charset[(int)((cvalue * charset.length - 1)/255)]+" "); } sb.append("\r\n"); } }catch(ioexception ex){ ex.printstacktrace(); } imgstring = sb.tostring(); return this; } /*图像文件预处理:将图片压缩到 最长边为 100px*/ private bufferedimage compressimage(bufferedimage srcimg){ int h = srcimg.getheight(); int w = srcimg.getwidth(); if(math.max(h,w)<=100) return srcimg; int new_h; int new_w; if(w>h){ new_w = 100; new_h = 100*h/w ; }else{ new_h = 100; new_w = 100*w/h; } bufferedimage smallimg = new bufferedimage(new_w,new_h,srcimg.gettype()); graphics g = smallimg.getgraphics(); g.drawimage(srcimg,0,0,new_w,new_h,null); g.dispose(); return smallimg; } /*将字符串保存为.txt文件*/ public void saveastxt(string filename){ try{ printwriter out = new printwriter(new bufferedwriter(new filewriter(filename))); for(int i = 0;i<imgstring.length();i++){ out.print(imgstring.charat(i)); } out.close(); }catch(ioexception ex){ ex.printstacktrace(); } } /*批处理图像文件*/ public static void batchimgfile(string srcfile, string tragetfile){ file folder = new file(tragetfile); //生成图片的文件夹 file srcfolder = new file(srcfile); if(!folder.exists() || !folder.isdirectory()) folder.mkdirs(); imageprocesser processer = new imageprocesser(); file[] filelist = srcfolder.listfiles(); for(int i=0;i<filelist.length;i++){ if(!filelist[i].isfile()) continue; processer.tobitmapconvert(filelist[i]); processer.saveastxt(tragetfile+"/"+(i+1)+".txt"); system.out.println(filelist[i].getname()+" is converted!"); } system.out.println("all img were converted!"); } }
点击查看:参考链接。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
上一篇: 福昕助力政法智能化建设