java文字转换为图片

来源:百度文库 编辑:神马文学网 时间:2024/04/29 08:26:35

Servlet:

package servlet;

import java.io.*;
import java.awt.*;
import java.awt.image.*;
import javax.servlet.*;
import javax.servlet.http.*;
import com.sun.image.codec.jpeg.*;

public class FontToImage extends HttpServlet {


protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
    {
   request.getParameter("");
        response.setContentType("image/jpeg");
        createImage(response.getOutputStream(),y,x);
    }
    private void createImage(OutputStream out,int y, int x) {
      
    //传过来的批注内容,及签名人等
       String sname = person.getRealname();
   String stime = one.getFlowtime().toString().substring(0,10);
   String s = one.getFlowsimple();
   //文字的长度
   int k = s.length();
   //每10个字为一行
   int n = 10;
   int count = k / n;

   //用来存储
   int m = count;
   if (count * n < k) {
    m = count + 1;
   }
   String ss[] = new String[m];

   if (count > 0) {
    for (int i = 1; i <= count; i++) {
     ss[i - 1] = s.substring((i - 1) * n, i * n);
    }
   }

   if (count * n < k) {
    ss[m - 1] = s.substring(count * n, k);
   }
   //System.out.println("存储的长度:"+ss.length);
   //图片区域大小,x显示宽度,y表示高度

   //int x=(int)(y*1.2);
   BufferedImage img = new BufferedImage(x, y, BufferedImage.TYPE_INT_RGB);
   Graphics g = img.getGraphics();
   g.setColor(Color.white);
   g.fillRect(0, 0, img.getWidth(), img.getHeight());
   g.setColor(Color.black);

   //调整文字大小
   int row = ss.length ;//内容共有row行
   int h1=40;//名字的高度
   int h2=20;//时间的高度
   int he = (y-60) / row;//每行的高度

   int startSize = x / 6;//名字的大小固定
   int fontSize = x / n;//刚开始每行每个字的大小
   int endSize = x / stime.length();//时间的大小固定

   Font mmFont = new Font("隶书", Font.BOLD, startSize);
   g.setFont(mmFont);
   g.drawString(sname, 0, h1);

   for (int i = 0; i < ss.length; i++) {
    Font mFont = new Font("宋体", Font.PLAIN, fontSize);
    g.setFont(mFont);
    g.drawString(ss[i], 0, (he * i+20)+40);
   }
   Font meFont = new Font("仿宋", Font.PLAIN, endSize);
   g.setFont(meFont);
   g.drawString(stime, 0,( he * ss.length )+60);    try  
    {  
    JPEGImageEncoder coder=JPEGCodec.createJPEGEncoder(out);  
    coder.encode(img);
   
    out.close();  
    }  
    catch(Exception   e)  
    {  
    e.printStackTrace();  
    }
    }
    }

 

JSP:

添加servlet路径