验证码不显示imageio异常

今天遇到一个问题,部署环境时验证码不出来,一直报image的io异常:

解决1:换一种输出方式

<%@ page language="java" contentType="image/jpeg" pageEncoding="GBK"%>
<%@ page import="java.awt.*"%>
<%@ page import="java.awt.image.*"%>
<%@ page import="java.util.*"%>
<%@ page import="javax.imageio.*"%>
<%@ page import="com.sun.image.codec.jpeg.JPEGCodec,com.sun.image.codec.jpeg.JPEGImageEncoder"%>



<%!
 Color getRandColor(int fc,int bc){
	Random random=new Random();
	if(fc>255)fc=255;
	if(bc>255)bc=255;
	int r=fc+random.nextInt(bc-fc);
	int g=fc+random.nextInt(bc-fc);
	int b=fc+random.nextInt(bc-fc);  
	return new Color(r,g,b);
}
%>
<%
int width=60,height=20;
BufferedImage image=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
Graphics g=image.getGraphics();
Random random=new Random();
g.setColor(getRandColor(200,250));
g.fillRect(0,0,width,height);
g.setFont(new Font("Times New Roman",Font.PLAIN,18));
g.setColor(getRandColor(160,200));
for(int i=0;i<155;i++){
	int x=random.nextInt(width);
	int y=random.nextInt(height);
	int x1=random.nextInt(12);
	int y1=random.nextInt(12);
	g.drawLine(x,y,x+x1,y+y1);
}
//get the random number
String sRand="";
for(int i=0;i<4;i++){
	String rand=String.valueOf(random.nextInt(10));
	sRand+=rand;
	g.setColor(new Color(20+random.nextInt(110),20+random.nextInt(110),20+random.nextInt(110)));
	g.drawString(rand,13*i+6,16);
}
//put the checkNumber into session
session.setAttribute("verify_code",sRand);
response.reset(); //如果不加此句,在weblogic下,验证码不显示。
g.dispose();
// ImageIO.write(image,"JPEG",response.getOutputStream()); 
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(response.getOutputStream());
encoder.encode(image); 

%>



 

解决2:在tomcat里目录下加一个temp文件夹

javax.imageio.IIOException: Can't create output stream! 

javax.imageio.ImageIO.write(ImageIO.java:1521) 


网上搜此问题,有说法是与JDK有关,并给出解决方案:


把

ImageIO.write(image, "jpeg", response.getOutputStream());

修改为
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(response.getOutputStream());

encoder.encode(image); 


//jsp上要增加com.sun.image.codec.jpeg.JPEGCodec,com.sun.image.codec.jpeg.JPEGImageEncoder这些类的import

经验证,是可以解决问题的。

但是。。。,原因怎会是JDK?我这个环境几分钟前还是正常的,中间没有安装过JDK或者修改环境变量

检查tomcat的日志,终于真相大白:

javax.imageio.IIOException: Can't create output stream!

 at javax.imageio.ImageIO.write(ImageIO.java:1521)

Caused by: javax.imageio.IIOException: Can't create cache file!

 at javax.imageio.ImageIO.createImageOutputStream(ImageIO.java:395)

 at javax.imageio.ImageIO.write(ImageIO.java:1519)

 ... 34 more
Caused by: java.io.IOException: 系统找不到指定的路径。

原来是ImageIO.write(image, "jpeg", response.getOutputStream());

需要写缓冲文件,但是写文件不成功。

手动创建temp目录,问题解决!

 

你可能感兴趣的:(tomcat)