"Test Class"
1 Public Static voidMain (string[] args)2 {3 Try4 {5File textfile =NewFile ("F:\\java56 class \\eclipse-SDK-4.2-win32\\1.txt");6File ImageFile =NewFile ("F:\\java56 class \\eclipse-SDK-4.2-win32\\1.png");7Texttoimage Texttoimage =Newtexttoimage (Textfile, imagefile);8 Texttoimage.convert ();9 }Ten Catch(Exception e) One { A e.printstacktrace (); - } -}
"Convert text to Picture class"
1 import Java.awt.Color;2 import Java.awt.Font;3 import java.awt.Graphics;4 import java.awt.image.BufferedImage;5 import Java.io.BufferedReader;6 import Java.io.File;7 import java.io.FileNotFoundException;8 import Java.io.FileOutputStream;9 import Java.io.FileReader;Ten import java.io.IOException; One import Com.sun.image.codec.jpeg.JPEGImageEncoder; A import Com.sun.image.codec.jpeg.JPEGCodec; - - Public classTexttoimage { the - /** Text File*/ - PrivateFile textfile; - /** Picture File*/ + PrivateFile ImageFile; - /** Picture*/ + Privatebufferedimage image; A /** Picture Width*/ at PrivateFinalintImage_width = $; - /** Picture Height*/ - PrivateFinalintImage_height = -; - /** Image Type*/ - PrivateFinalintImage_type =Bufferedimage.type_int_rgb; - in /** - * Constructor Function to * @param textfile text file + * @param imagefile picture file - */ the Publictexttoimage (File textfile,file imagefile) { * This. Textfile =textfile; $ This. ImageFile =ImageFile;Panax Notoginseng This. Image =Newbufferedimage (Image_width, Image_height, image_type); - } the + /** A * The text in the file, write to the picture to save the * @return Boolean true, write succeeded; False, write failed + */ - PublicBoolean convert () { $ $ //reading text Files -BufferedReader reader =NULL; - Try { theReader =NewBufferedReader (NewFileReader (textfile)); -}Catch(FileNotFoundException e) {Wuyi e.printstacktrace (); the return false; - } Wu - //Get Image Context AboutGraphics g =creategraphics (image); $ String Line; - //picture Chinese Bank High -FinalintY_lineheight = the; - intLineNum =1; A Try { + while(line = Reader.readline ())! =NULL){ theg.DrawString (Line,0, LineNum *y_lineheight); -linenum++; $ } the g.dispose (); the the //Save as JPG image theFileOutputStream fos =NewFileOutputStream (imagefile); -JPEGImageEncoder encoder =Jpegcodec.createjpegencoder (FOS); in Encoder.encode (image); the fos.close (); the}Catch(IOException e) { About e.printstacktrace (); the return false; the } the return true; + } - the /**Bayi * Get to Image context the * @param image Image the * @return Graphics - */ - PrivateGraphics creategraphics (bufferedimage image) { theGraphics g =image.creategraphics (); theG.setcolor (NULL);//Set Background color theG.fillrect (0,0, Image_width, image_height);//Draw Background theG.setcolor (Color.Black);//Set foreground color -G.setfont (NewFont ("Microsoft Ya-Black", Font.plain, the));//Set Font the returnG; the}
"Turn txt text to picture"