我尝试使用JCaptcha组件制作验证码,并且需要在相关的servlet中对图像进行编码。因此,根据JCaptcha教程,我应该使用JPEGImageEncoder,并且它与JDK7不兼容。
我还可以做些什么?
这是代码的相关部分:

     ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
     BufferedImage challenge =
             CaptchaServiceSingleton.getInstance().getImageChallengeForID(captchaId,
                     httpServletRequest.getLocale());
   JPEGImageEncoder jpegEncoder =
                 JPEGCodec.createJPEGEncoder(jpegOutputStream);
         jpegEncoder.encode(challenge);
     } catch (IllegalArgumentException e) {
         httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
         return;
     } catch (CaptchaServiceException e) {
         httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
         return;
     }

最佳答案

使用ImageIO

// Image writer
    ImageWriter imageWriter = (ImageWriter)ImageIO.getImageWritersBySuffix("jpeg").next();
    ImageOutputStream ios = ImageIO.createImageOutputStream(jpegOutputStream);
    imageWriter.setOutput(ios);
    IIOMetadata imageMetaData = imageWriter.getDefaultImageMetadata(new ImageTypeSpecifier(challenge), null);
    imageWriter.write(imageMetaData, new IIOImage(challenge, null, null), null);


这将替换不推荐使用的JPEG功能

07-27 18:22