给你个连接参考一下。
这个是正确的,我测试过。
http://www.javaresearch.org/article/showarticle.jsp?column=544&thread=18121

解决方案 »

  1.   

    response.getOutputStream(),它可以得到一个己经实例了的流吗?
      

  2.   

    <%@ page contentType="image/jpeg" 
        import="java.awt.*,
            java.awt.image.*,
    java.awt.Color,
                java.awt.Font,
                java.awt.Graphics,
                java.awt.Image,
                java.awt.image.BufferedImage,
                java.io.IOException,
                java.util.Random,
    com.sun.image.codec.jpeg.*,
    java.util.*"
    %>
    <%
    String sRand = null;
    int width = 80,height = 20;
        BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_BGR); // 在内存中创建图象
        Graphics g = image.getGraphics();// 获取图形上下文
        Random   random = new  Random();//生成随机类  
        int fc = 88,bc = 100;
        if(fc>255) fc=255;
        if(bc>255) bc=255;
        int r=fc+random.nextInt(bc-fc);
        int gr=fc+random.nextInt(bc-fc);
        int b=fc+random.nextInt(bc-fc);
                    
    Color color =  new Color(r,gr,b);
        g.setColor(color);// 初始化背景色
        g.fillRect(0,0,width,height);//初始化
        //g.drawRect(0,0,width-1,height-1);//画边框
        g.setFont(new Font("Times New Roman",Font.PLAIN,18));//设定字体    fc = 100;bc = 200;
                    
        r=fc+random.nextInt(bc-fc);
        gr=fc+random.nextInt(bc-fc);
        b=fc+random.nextInt(bc-fc);    color =  new Color(r,gr,b);
        g.setColor(color);//重新设置干扰线颜色
        random = new  Random();//生成随机类 
        for (int i=0; i<88; i++){
            int x,y;
            int x1,y1;
            x = random.nextInt(width);
            y = random.nextInt(height);
            x1 = random.nextInt(88);
            y1 = random.nextInt(88);
            g.drawLine(x,y,x+x1,y+y1);
        }
        
    for (int i=0;i<4;i++){
    String rand=String.valueOf(random.nextInt(10));
            sRand+=rand;
            // 将认证码显示到图象中
            g.setColor(new Color(5+random.nextInt(50),10+random.nextInt(80),10+random.nextInt(80)));
            //调用函数出来的颜色相同,直接生成
            g.drawString(rand,13*i+6,16);
        }
        
    g.dispose(); ServletOutputStream sos = response.getOutputStream();
    JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(sos);
    encoder.encode(image);
    %>