Servlet如何与图像或图片Image做交互?

Servlet与Image:
马克- to-win:马克 java社区:防盗版实名手机尾号: 73203。
本节介绍Servlet如何与图像或者图片做交互。在现实当中,我们常见的最重要的应用就是登录时,有时管你要验证码,省得你是机器人黑客在登录,无限的试用户名和密码。还有应用就是:html当中无法显示中文图片时。

下例是服务器往客户端传回一张图片(gif或jpeg)。



例:4.4.1

package com;
import java.io.IOException;
import java.io.InputStream;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ServletHello1 extends HttpServlet {
    /* image/gif变成jpeg,换成jpeg的图片,照样成功。 */
    private static final String CONTENT_TYPE = "image/gif";

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType(CONTENT_TYPE);
        ServletContext ctx = getServletContext();
        /* 图片在WebModule的根目录下 */
        InputStream is = ctx.getResourceAsStream("p_twostar.gif");
        int len = is.available();
        // response.setContentLength(len);
        ServletOutputStream out = response.getOutputStream();
        byte[] in = new byte[4096];
        int i = 0;
        /* public int read(byte[] b) throws IOException Reads some number of
         * bytes from the input stream and stores them into the buffer array b.
         * The number of bytes read is, at most, equal to the length of b.
         * Returns: the total number of bytes read into the buffer, or -1 is
         * there is no more data because the end of the stream has been reached.
         */
        while ((i = is.read(in)) != -1) {
            /*
             * write(byte[] b, int off, int len) Writes len bytes from the
             * specified byte array starting at offset off to this output
             * stream.
             */
            out.write(in, 0, i);
        }
        is.close();
    }
}