この記事の例は、あなたの参照のために画像を文字図面に変換するJavaの特定のコードを共有します。特定のコンテンツは次のとおりです
public class imageProcesser {private static final char [] charset1 = {'m'、 '8'、 'v'、 '|': '、'、 '、' '}; //デフォルトのキャラクターマテリアルセットプライベートチャー[] charset; //文字描画マテリアルセットプライベートストリングimgstring = ""; //変換された文字列の保存} // 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( "ファイルは存在しません!"); System.Exit(1); }色の色; try {bufferedimage buff = imageio.read(imagefile); // bufferedimageストリームバフ= compressimage(buff)などの画像ファイルをロードします。 int bitmaph = buff.getheigh(); int bitmapw = buff.getWidth(); //画像のピクセルを徐々にスキャンし、RGB値を読み取り、平均値を取得し、CharSetから対応する文字素材を取得し、(int y = 0; y <bitmaph; y ++){for(x <bitmapw; x ++){int rgb.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();これを返します。 } /*画像ファイルプリプロセシング:画像を最長のエッジに100pxに圧縮します* / private bufferedimage Compressimage(bufferedimage srcimg){int h = srcimg.getheigh(); int w = srcimg.getWidth(); if(math.max(h、w)<= 100)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());グラフィックg = smallimg.getgraphics(); G.drawimage(srcimg、0,0、new_w、new_h、null); g.dispose(); smallimgを返します。 } /*文字列を.txtファイルとして保存* / public void saveastxt(string filename){try {printwriter out = new Printwriter(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); //画像ファイルを生成するフォルダーsrcfolder = new file(srcfile); if(!folder.exists()||!folder.isdirectory())folder.mkdirs(); ImageProcesser processor = new ImageProcesser(); file [] filelist = srcfolder.listfiles(); for(int i = 0; i <filelist.length; i ++){if(!filelist [i] .isfile())continue; processor.tobitmapconvert(filelist [i]); processor.saveastxt(tragetfile+"/"+(i+1)+"。txt"); system.out.println(filelist [i] .getname()+"is converted!"); } system.out.println( "すべてのIMGが変換されました!"); }}クリックして表示:リンクリンク。
上記はこの記事のすべての内容です。みんなの学習に役立つことを願っています。誰もがwulin.comをもっとサポートすることを願っています。