分享

JSP给图片添加文字

 ChirMan 猫 2006-07-25



<%@ page autoFlush="false" contentType="text/html;charset=GBK" import="java.io.FileInputStream,
java.io.FileOutputStream,
java.awt.*,
java.awt.image.*,
com.sun.image.codec.jpeg.*,
java.util.*"%>

<%  
  out.clear();  
  response.addHeader("pragma","NO-cache");  
  response.addHeader("Cache-Control","no-cache");  
  response.addDateHeader("Expries",0);  
  String FileName = "E:\\2.jpg";
  String OutFileName = "C:\\ww.jpg";

  //创建一个FileInputStream对象从源图片获取数据流  
  FileInputStream sFile = new FileInputStream(FileName);

  //创建一个Image对象并以源图片数据流填充
 Image src = javax.imageio.ImageIO.read(sFile);  
 int width = src.getWidth(null); //得到源图宽  
 int height = src.getHeight(null); //得到源图长  
 if (width>70 && height>30){
     //创建一个BufferedImage来作为图像操作容器
     BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

      //创建一个绘图环境来进行绘制图象
   Graphics g = image.getGraphics();

     //将原图像数据流载入这个BufferedImage  
   g.drawImage(src,0,0,width,height,null);

     //设定文本字体
     g.setFont(new Font("宋体",Font.PLAIN,48));  
 
   //设定文本
   String rand = "中国";

     //设定文本颜色  
     g.setColor(Color.black);

   //向BufferedImage写入文本字符
   g.drawString(rand,20,50);  

   //使更改生效
   g.dispose();    

   //创建输出文件流
   FileOutputStream outi = new FileOutputStream(OutFileName);  

   //创建JPEG编码对象
   JPEGImageEncoder encodera = JPEGCodec.createJPEGEncoder(outi);    

   //对这个BufferedImage (image)进行JPEG编码
   encodera.encode(image);  
   outi.close(); //关闭输出文件流  
 }
%>


    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约