ImageIO写入方法 - javax imageio IIOException无法创建输出流

3
protected void doGet(HttpServletRequest req, HttpServletResponse response)
        throws IOException, ServletException {
    // Expire response
    try {
        //   
        ByteArrayOutputStream imgOutputStream = new ByteArrayOutputStream();
        byte[] captchaBytes;

        BufferedImage image = new BufferedImage(width, height,
                BufferedImage.TYPE_INT_RGB);
        Graphics2D graphics2D = image.createGraphics();
        Hashtable<TextAttribute, Object> map = new Hashtable<TextAttribute, Object>();
        Random r = new Random();
        String token = Long.toString(Math.abs(r.nextLong()), 36);
        String ch = token.substring(0, 6);
        Color c = new Color(0.6662f, 0.4569f, 0.3232f);
        GradientPaint gp = new GradientPaint(30, 30, c, 15, 25,
                Color.white, true);
        graphics2D.setPaint(gp);
        Font font = new Font("Verdana", Font.CENTER_BASELINE, 26);
        graphics2D.setFont(font);
        graphics2D.drawString(ch, 2, 22);
        graphics2D.dispose();

        HttpSession session = req.getSession(true);
        session.setAttribute(CAPTCHA_KEY, ch);

        OutputStream outputStream = response.getOutputStream();
        ImageIO.write(image, "jpeg", imgOutputStream);
        captchaBytes = imgOutputStream.toByteArray();
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Max-Age", 0);
        response.setContentType("image/jpeg");
        outputStream.write(captchaBytes);
        outputStream.close();
        utils.PQSoftLogger.getInstance().log(
                "Captch servlet: " + image.toString());
    } catch (Exception e) {
        utils.PQSoftLogger.getInstance().log(
                e.toString() + ":" + e.getMessage());
        for (StackTraceElement s : e.getStackTrace()) {
            utils.PQSoftLogger.getInstance().log(
                    s.getLineNumber() + ":" + s.getMethodName() + ":"
                            + s.getFileName());
        }
    } finally {
        utils.PQSoftLogger.getInstance().log("temp dir-"+System.getProperty("java.io.tmpdir"));
        utils.PQSoftLogger.getInstance().log("Captch servlet executed");
    }
}

在调用Tomcat服务器环境中的servlet时,使用ImageIO.write方法会抛出以下异常:"javax.imageio.IIOException: Can't create output stream!"。但是在本地系统上它可以正常工作。

你有几行堆栈跟踪吗? - Harald K
2个回答

6

我遇到了同样的问题。我之前删除了Tomcat安装目录下的temp目录。Tomcat在启动时不会自动创建这个目录。重新添加temp目录后,问题得到解决。


谢谢。我也遇到了同样的问题。 - Ranjeet

2

我记得很久以前曾经成功解决过类似的问题。但是如果我没记错的话,这个问题与在临时目录创建某种文件缓存有关。

所以,如果目录${CATALINA_TMPDIR}TOMCAT_HOME/temp)不存在或者它不可被运行tomcat的用户写入,那么可能会发生这种情况。

希望对您有所帮助。


2
听起来很有可能。如果确实是这种情况,您也可以通过禁用ImageIO文件缓存并使用setUseCache(false)来解决问题。 - Harald K

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接