1 /** 2 There are many dynamically generated images that are done using Servlets, and the code is more, and the code here is to generate image files with commands. 3 Create a BufferedImage object, put your "picture" into this buffer,4 Open a file, encode the image stream and enter the file, so that a JPG file appears. 5* /
1 ImportJava.awt.Color;2 ImportJava.awt.Graphics;3 ImportJava.awt.image.BufferedImage;4 ImportJava.io.BufferedOutputStream;5 Importjava.io.FileNotFoundException;6 ImportJava.io.FileOutputStream;7 Importjava.io.IOException;8 ImportJava.util.Vector;9 Importcom.sun.image.codec.jpeg.*;Ten One Public classTregraphics { A bufferedimage image; - - //create a JPG file under the specified path the Public voidcreatejpg (String path) { - Try{ -FileOutputStream fos =NewFileOutputStream (path); -Bufferedoutputstream BOS =NewBufferedoutputstream (FOS); +JPEGImageEncoder encoder =Jpegcodec.createjpegencoder (BOS); - Encoder.encode (image); + bos.close (); A at}Catch(FileNotFoundException fnfe) { - System.out.println (FNFE); -}Catch(IOException IoE) { - System.out.println (IOE); - } - } in Public Static voidMain (string[] args) { - intwidth=400,height=200; to intXlength = 300,ylength = 150; + intCount =5; -Vector data =NewVector (); theData.addelement (NewInteger (100)); *Data.addelement (NewInteger (120)); $Data.addelement (NewInteger (150));Panax NotoginsengData.addelement (NewInteger (40)); -Data.addelement (NewInteger (5)); theTregraphics TG =Newtregraphics (); +Tg.image =NewBufferedImage (WIDTH,HEIGHT,BUFFEREDIMAGE.TYPE_INT_RGB); AGraphics g =tg.image.getGraphics (); the //Draw coordinates + G.setcolor (color.white); -G.fillrect (0, 0, width, height); $ G.setcolor (color.blue); $G.drawline (10,height-10,10,height-10-ylength); -G.drawline (height-10, 10+xlength, height-10); - //Connection the intYto; - intYfrom = ((Integer) (Data.elementat (0)) . Intvalue ();Wuyi for(inti=1;i<count;i++){ theYto =( (Integer) (Data.elementat (i))). Intvalue (); -G.drawline (10+i*xlength/count, height-10, 10+i*xlength/count, height-15); WuG.drawline (i-1) *xlength/count, Yfrom, 10+i*xlength/count, yto); -Yfrom =Yto; About } $Tg.createjpg ("D:aaa.jpg"); - } -}
Generate JPG in Java