- public class ImageServlet extends HttpServlet {
- //显示gif图片
- private static final String gif = "image/gif;charset=GB2312";
- //显示jpeg图片
- private static final String jpg = "image/jpeg;charset=GB2312";
- public ImageServlet() {
- super();
- }
- public void destroy() {
- super.destroy(); // Just puts "destroy" string in log
- }
- public void doGet(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- //我這里是相对路径,请根据自己实际情况调整。
- String imagePath = "/img/b1.jpg";
- //获得输出流
- OutputStream stream = response.getOutputStream();
- if (imagePath.toLowerCase().endsWith("jpg")) {
- //设置contentType,平时用的都是“html/text”
- response.setContentType(jpg);
- //获得image文件的绝对路径
- imagePath = getServletContext().getRealPath(imagePath);
- InputStream in = new FileInputStream(new File(imagePath));
- //下面将文件编码
- JPEGImageDecoder decoder = JPEGCodec
- .createJPEGDecoder(in);
- BufferedImage buffer = decoder.decodeAsBufferedImage();
- JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(stream);
- encoder.encode(buffer);
- in.close();
- }
- }
- public void doPost(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- doGet(request, response);
- }
- public void init() throws ServletException {
- }
- }