在网站上下的专家写的demo,就是通过给定img的src一个servlet路径,来获取图片的。可是我将demo部署到tomcat运行显示的却是红叉叉,肯定是通过测试的,可为啥我这不行呢?下面是源代码,肯定是没问题的,我用的是IE7,火狐也不行。请知情人指点迷津!我现在真的怀疑,这个方法的可行性,或是自己太笨!------------------------------------------------------------------------------------------------------
package net.xdevelop.merge;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.awt.*;
import java.awt.image.*;
import com.sun.image.codec.jpeg.*;import net.xdevelop.util.ParamUtil;
/**
 * 将文字用指定的字体,颜色和大小,嵌入指定图片的指定位置,调用参数:
 * text:     要嵌的文字
 * imageFile:  JPG图片的虚拟路径
 * x:      文字输出的起始X坐标位置
 * y:      文字输出的起始Y坐标位置
 * fontColor:  字体颜色(例fontColor=FFFFFF)
 * fontSize:  字体大小
 * fontStyle:  字体风格(斜体,粗体等)
 * fontName:  字体名称(如仿宋体,宋体等)
 */
public class TextIntoImage extends HttpServlet {
    private static final String CONTENT_TYPE = "image/jpeg;charset=GBK";
    public void init() throws ServletException {
    }
    /** Process the HTTP Get request */
    public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
        doPost(request,response);
    }
    //---------------------------------------------------------------------------------------------
    /** Process the HTTP Post request */
    public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
        response.setContentType(CONTENT_TYPE);
        String text = "";               //要嵌的文字
        String imageFile = "";          //被嵌的图片的虚拟路径
        int x = 0;                      //坐标
        int y = 0;
        String fontColor = "";          //字体颜色
        int fontSize = 0;               //字体大小
        String fontStyle = "";          //字体风格(斜体,粗体等)
        String fontName = "";           //字体名称
        try {
            //取得参数(ParamUtil类请参看后面附的ParamUtil类代码)
            text = ParamUtil.getParameter(request,"text");
            imageFile = ParamUtil.getParameter(request,"imageFile");
            x = ParamUtil.getIntParameter(request,"x",0);
            y = ParamUtil.getIntParameter(request,"y",0);
            fontColor = ParamUtil.getParameter(request,"fontColor");
            fontSize = ParamUtil.getIntParameter(request,"fontSize",16);
            fontStyle = ParamUtil.getParameter(request,"fontStyle");
            fontName = ParamUtil.getParameter(request,"fontName");
        }
        catch(Exception e) {
            e.printStackTrace();
        }
        ServletOutputStream output=response.getOutputStream();
        if(imageFile.toLowerCase().endsWith(".jpeg")||imageFile.toLowerCase().endsWith(".jpg")) {
            imageFile = getServletContext().getRealPath(imageFile);
            InputStream imageIn = new FileInputStream(new File(imageFile));
            JPEGImageDecoder decoder = JPEGCodec.createJPEGDecoder(imageIn);
            BufferedImage image = decoder.decodeAsBufferedImage();
            Graphics g=image.getGraphics();
            //设置颜色
            g.setColor(new Color(Integer.parseInt(fontColor,16)));
            //设置字体
            Font mFont = new Font(fontName,Font.PLAIN,fontSize);//默认字体
            if(fontStyle.equalsIgnoreCase("italic")) mFont=new Font(fontName,Font.ITALIC,fontSize);
            if(fontStyle.equalsIgnoreCase("bold")) mFont=new Font(fontName,Font.BOLD,fontSize);
            if(fontStyle.equalsIgnoreCase("plain")) mFont=new Font(fontName,Font.PLAIN,fontSize);
            g.setFont(mFont);
            //输出文字
            g.drawString(text,x,y);
            //输出数据流
            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(output);
            encoder.encode(image);
            imageIn.close();
        }
        output.close();
    }
}//////////
------------------------------------------------------------------------------------------------------
package net.xdevelop.util;import javax.servlet.*;
public class ParamUtil {
  /**
   * 获得request中指定名称的参数值,若有中文乱码问题请增加转码部分
   * @param request ServletRequest对象
   * @param paramName 参数名称
   * @return 如果该变量值存在则返回该值,否则返回""
   */
  public static String getParameter( ServletRequest request, String paramName ) {
    String temp = request.getParameter(paramName);
    if( temp != null && !temp.equals("") ) {
        //若有中文问题,在此添加转码代码,例:temp = new String(temp.getBytes("8859_1"), "GB2312");
        return temp;
    }
    else {
      return "";
    }
  }
  /**
   * 获得request中的int型参数值
   * @param request ServletRequest对象
   * @param paramName 参数名称
   * @param defaultNum 默认值,如果没有返回该值
   * @return 如果该参数值存在则返回其转换为int型的值,否则返回defaultNum
   */
  public static int getIntParameter( ServletRequest request, String paramName, int defaultNum ) {
    String temp = request.getParameter(paramName);
    if( temp != null && !temp.equals("") ) {
      int num = defaultNum;
      try {
          num = Integer.parseInt(temp);
      }
      catch( Exception ignored ) {
      }
      return num;
    }
    else {
      return defaultNum;
    }
  }
}///////////
------------------------------------------------------------------------------------------------------
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>textintoimage</servlet-name>
<servlet-class>net.xdevelop.merge.TextIntoImage</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>textintoimage</servlet-name>
<url-pattern>/TextIntoImage</url-pattern>
</servlet-mapping></web-app>
------------------------------------------------------------------------------------------------------
index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="gbk"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">    
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
  </head>
  
  <body>
    <img border="0" src="/TextIntoImage?text=HotPotFocus&imageFile=/bg.jpg&x=20&y=20&fontColor=FFFFFF&fontStyle=bold&fontName=Roman&fontSize=16" />
  </body>
</html>
------------------------------------------------------------------------------------------------------一共就这么点东西,咋就不行呢!奇怪的是,使用img的src指向servlet的路径是红叉叉,可直接在地址栏里输入这个地址访问就能获取图片,为什么呢?都说是可行的啊!可我这咋就不行呢?原因会是什么呢?

解决方案 »

  1.   

    此回复为自动发出,仅用于显示而已,并无任何其他特殊作用
    楼主【IceWee】截止到2008-07-28 10:47:07的历史汇总数据(不包括此帖):
    发帖的总数量:5                        发帖的总分数:60                       每贴平均分数:12                       
    回帖的总数量:7                        得分贴总数量:2                        回帖的得分率:28%                      
    结贴的总数量:4                        结贴的总分数:40                       
    无满意结贴数:2                        无满意结贴分:40                       
    未结的帖子数:1                        未结的总分数:20                       
    结贴的百分比:80.00 %               结分的百分比:66.67 %                  
    无满意结贴率:50.00 %               无满意结分率:100.00%                  
    楼主加油
      

  2.   

    1,可以
    2, 你应当使用doGet
    3,除了图片内容,不要多输出任何字符
    4,在浏览器直接输入
    /TextIntoImage?text=HotPotFocus&imageFile=/bg.jpg&x=20&y=20&fontColor=FFFFFF&fontStyle=bold&fontName=Roman&fontSize=16
    看是否显示,看源代码是什么
      

  3.   

    也不知道为什么,把那DEMO放到tomcat的 webapp的 ROOT目录下就可以显示!  没仔细研究,不过应该还是路径问题。源码中的getServletContext().getRealPath(path),也不知道返回哪去了!哎