Servlet如何與圖像或圖片Image做交互?

Servlet與Image:
馬克- to-win:馬克 java社區(qū):防盜版實名手機尾號: 73203。
本節(jié)介紹Servlet如何與圖像或者圖片做交互。在現(xiàn)實當中,我們常見的最重要的應(yīng)用就是登錄時,有時管你要驗證碼,省得你是機器人黑客在登錄,無限的試用戶名和密碼。還有應(yīng)用就是:html當中無法顯示中文圖片時。

下例是服務(wù)器往客戶端傳回一張圖片(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();
    }
}