1 16 package dlog4j.util.image; 17 18 import java.awt.*; 19 import java.awt.image.*; 20 import java.io.FileOutputStream ; 21 import java.io.IOException ; 22 import java.io.OutputStream ; 23 24 import javax.imageio.ImageIO ; 25 26 import org.apache.commons.lang.RandomStringUtils; 27 32 public class RandomImageGenerator { 33 34 public static String random() { 35 return RandomStringUtils.randomNumeric(4); 36 } 37 43 public static void render(String num, OutputStream out) throws IOException { 44 if(num.getBytes().length>4) 45 throw new IllegalArgumentException ("The length of param num cannot exceed 4."); 46 int width = 40; 47 int height = 15; 48 BufferedImage bi = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB); 49 Graphics2D g = (Graphics2D)bi.getGraphics(); 50 g.setColor(Color.WHITE); 51 g.fillRect(0,0,width,height); 52 Font mFont = new Font("Tahoma", Font.PLAIN, 14); 53 g.setFont(mFont); 54 g.setColor(Color.BLACK); 55 g.drawString(num,2,13); 56 ImageIO.write(bi,"jpg",out); 57 } 58 59 public static void main(String [] args) throws IOException { 60 String num = random(); 61 System.out.println(num); 62 render(num,new FileOutputStream ("D:\\test.jpg")); 63 System.out.println("Image generated."); 64 } 65 } 66 | Popular Tags |