当前位置: 代码迷 >> 综合 >> 通过流的方式输出图片
  详细解决方案

通过流的方式输出图片

热度:27   发布时间:2024-01-16 22:04:25.0

通过servlet的方式输出图片流 (类似验证码的生成)

 这个模块挺大,我仅说说用servlet显示图片部分。我先说说用servlet显示图片的一个流程:

 1. 设置response的输出类型:

    对应的语句--response.setContentType("image/gif;charset=GB2312") ,response  

    便能输出gif图片,"image/gif;charset=GB2312"便是输出类型,当然你可以输出

    "image/jpg;charset=GB2312"类型文件。

 2. 得到文件流:

    servlet是以流的形式件图片文件从服务器读出,通过response将流发到浏览器的。

 3. 得到输出流:

    对应的语句--OutputStream output = response.getOutputStream();

    当然,处理图片文件需要以二进制形式的流。

 4. 文件流的编码(但也不一定必须编码的,如果不是文件流,则必须编码)

    所以我给大家一个用编码的代码和不用编码的代码.

  顺便说一句,sun公司仅提供了jpg图片文件的编码api。

    

    我想基本流程都讲完了,下面我把代码拿给大家看一下,大家自然一目了然了:

package xjw.personal.servet;

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

import com.sun.image.codec.jpeg.*;//sun公司仅提供了jpg图片文件的编码api

import javax.imageio.stream.*;

import java.awt.*;

import java.awt.image.BufferedImage;

public class ShowPicture  extends HttpServlet

{

     private static final String GIF="image/gif;charset=GB2312";//设定输出的类型

     private static final String JPG="image/jpeg;charset=GB2312";

     public void init()  throws ServletException

     {

     }

     public void doGet(HttpServletRequest request, HttpServletResponse response)

                  throws IOException, ServletException

     {

        doPost(request, response);

     }

 

    public void doPost(HttpServletRequest request, HttpServletResponse response)

                 throws IOException, ServletException

   {

        

        String spec=request.getParameter("spec");//输出图片的类型的标志

     int int_spec=Integer.parseInt(spec);

        if(spec==1)    

        {

            String imagePath="/jfgg/b1.jpg";//图片相对web应用的位置

        }

        else

        {

              String imagePath="/jfgg/b2.gif";//图片相对web应用的位置

        }    

        

       OutputStream output = response.getOutputStream();//得到输出流

       if(imagePath.toLowerCase().endsWith(".jpg"))//使用编码处理文件流的情况:

      {

     response.setContentType(JPG);//设定输出的类型

          //得到图片的真实路径      

          imagePath = getServletContext().getRealPath(imagePath);

         //得到图片的文件流

          InputStream imageIn = new FileInputStream(new File(imagePath));

         //得到输入的编码器,将文件流

  相关解决方案