1 package com.Yasna.servlet; 2 3 import javax.servlet.http.HttpServlet ; 4 import javax.servlet.http.HttpServletResponse ; 5 import javax.servlet.http.HttpServletRequest ; 6 import javax.servlet.ServletConfig ; 7 import javax.servlet.ServletException ; 8 import javax.imageio.ImageIO ; 9 import java.awt.*; 10 import java.awt.font.FontRenderContext ; 11 import java.awt.geom.Rectangle2D ; 12 import java.awt.image.BufferedImage ; 13 import java.io.OutputStream ; 14 import java.io.FileInputStream ; 15 import java.io.File ; 16 import java.io.InputStream ; 17 18 70 71 74 public class ImageCodeGenerator extends HttpServlet { 75 private Font font; 76 private BufferedImage buffer; 77 private Graphics2D g2; 78 public void init (ServletConfig config) 79 throws ServletException { 80 System.setProperty( "java.awt.headless", "true" ); 81 buffer = new BufferedImage (1,1,BufferedImage.TYPE_INT_RGB); 82 g2 = buffer.createGraphics(); 83 try{ 84 font = Font.createFont(Font.TRUETYPE_FONT,getClass().getResourceAsStream("Teenick.ttf")); font = font.deriveFont(29.0f); 86 System.err.println("Yazd Initialized Font"); 87 } catch (Exception e){ 88 System.err.println("Exception in Yazd Servlet 0: " + e.getMessage()); 89 e.printStackTrace(); 90 } 91 super.init (config); 92 } 93 94 95 public void service (HttpServletRequest request, 96 HttpServletResponse response){ 97 String code = (String )request.getSession().getAttribute("YazdCode"); 98 99 sendImage(response,code); 100 101 } 102 103 private void sendImage(HttpServletResponse response,String code){ 104 try{ 105 106 107 buffer = new BufferedImage (90, 50, 109 BufferedImage.TYPE_INT_RGB); 110 g2 = buffer.createGraphics(); 111 g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, 112 RenderingHints.VALUE_ANTIALIAS_ON); 113 g2.setFont(font); 114 g2.setColor(Color.BLUE); 116 g2.fillRect(0,0,90,50); 117 g2.setColor(Color.WHITE); 118 g2.drawString(code,3,35); 119 120 121 response.setContentType("image/png"); 123 OutputStream os = response.getOutputStream(); 124 125 ImageIO.write(buffer, "png", os); 127 os.close(); 128 129 130 } catch (Exception e){ 131 System.err.println("Exception in Yazd Servlet: " + e.getMessage()); 132 e.printStackTrace(); 133 } 134 } 135 } 136 | Popular Tags |