?? imagehandlerservlet.java
字號:
package org.sunxin.lesson.jsp.ch24;
import java.awt.image.BufferedImage;
import javax.servlet.*;
import java.io.*;
import javax.servlet.http.*;
import com.sun.image.codec.jpeg.*;
import org.sunxin.lesson.jsp.util.PicZoom;
public class ImageHandlerServlet extends HttpServlet
{
protected void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, java.io.IOException
{
String strId=req.getParameter("id");
if(null==strId || "".equals(strId))
{
throw new ServletException("圖像參數錯誤!");
}
int id=Integer.parseInt(strId);
String srcImgFileName=null;
//此處為了簡單,所以使用了switch/case語句,硬編碼了images/1.jpg這幅圖片,
//讀者可以將圖像數據保存到數據庫中,根據請求的參數取出相應的圖片。
//或者直接保存在硬盤上,為所有的圖片文件做一個索引文件,
//得到請求參數后,通過查找索引文件得到圖片的路徑。
switch(id)
{
case 1:
srcImgFileName=getServletContext().getRealPath("/")+"images/1.jpg";
break;
case 2:
break;
default:
throw new ServletException("圖像參數錯誤!");
}
resp.setContentType("image/jpeg");
ServletOutputStream sos=resp.getOutputStream();
//調用PicZoom類的靜態方法zoom對原始圖像進行縮放。
BufferedImage buffImg=PicZoom.zoom(srcImgFileName,80,80);
//創建JPEG圖像編碼器,用于編碼內存中的圖像數據到JPEG數據輸出流。
JPEGImageEncoder jpgEncoder=JPEGCodec.createJPEGEncoder(sos);
//編碼BufferedImage對象到JPEG數據輸出流。
jpgEncoder.encode(buffImg);
sos.close();
}
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -