• 验证码工具类:
1
package com.newcapec.utils;

2
3
import com.sun.image.codec.jpeg.JPEGCodec;

4
import com.sun.image.codec.jpeg.JPEGImageEncoder;

5
6
import java.awt.*;

7
import java.awt.image.BufferedImage;

8
import java.io.FileOutputStream;

9
import java.io.IOException;

10
import java.io.OutputStream;

11
import java.util.Random;

12
13
/** 

14
 * <p>Title: ValidateCode.java</p>  

15
 * <p>Description: 验证码工具类</p>  

16
 */

17
public class ValidateCode {    

18
    // 图片的宽度。  

19
    private int width = 120;  

20
    // 图片的高度。  

21
    private int height = 40;  

22
    // 验证码字符个数  

23
    private int codeCount = 4;  

24
    // 验证码干扰线数  

25
    private int lineCount = 30;  

26
    // 验证码  

27
    private String code = null;  

28
    // 验证码图片Buffer  

29
    private BufferedImage buffImg = null;  

30
  

31
    private char[] codeSequence = { 'A','a', 'B','b', 'C','c', 'D','d', 'E','e', 'F','f', 'g','H','h',  

32
            'J','j', 'K','k','L', 'M','m', 'N','n', 'P','p', 'Q','q', 'R','r', 'S','s', 'T', 'U','u', 'V', 'W','w',  

33
            'X','x', 'Y', 'Z', '2', '3', '4', '5', '6', '7', '8', '9'};  

34
  

35
    // 生成随机数  

36
    private Random random = new Random();  

37
  

38
    public ValidateCode() {  

39
        this.createCode();  

40
    }  

41
  

42
    /** 

43
     *  

44
     * @param width 

45
     *            图片宽 

46
     * @param height 

47
     *            图片高 

48
     */  

49
    public ValidateCode(int width, int height) {  

50
        this.width = width;  

51
        this.height = height;  

52
        this.createCode();  

53
    }  

54
  

55
    /** 

56
     *  

57
     * @param width 

58
     *            图片宽 

59
     * @param height 

60
     *            图片高 

61
     * @param codeCount 

62
     *            字符个数 

63
     * @param lineCount 

64
     *            干扰线条数 

65
     */  

66
    public ValidateCode(int width, int height, int codeCount, int lineCount) {  

67
        this.width = width;  

68
        this.height = height;  

69
        this.codeCount = codeCount;  

70
        this.lineCount = lineCount;  

71
        this.createCode();  

72
    }  

73
  

74
    public void createCode() {  

75
        Random heightRandom = new Random();

76
        int codeX = 0;  

77
        int fontHeight = 0;  

78
        fontHeight = height-heightRandom.nextInt(7)-7;// 字体的高度  

79
        codeX = width / (codeCount+1);// 每个字符的宽度  

80
  

81
        // 图像buffer  

82
        buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);  

83
        Graphics2D g = buffImg.createGraphics();  

84
  

85
        // 将图像填充为白色  

86
        g.setColor(Color.WHITE);  

87
        g.fillRect(0, 0, width, height);  

88
  

89
        // 创建字体  

90
        ImgFontByte imgFont = new ImgFontByte();  

91
        Font font = imgFont.getFont(fontHeight);  

92
        g.setFont(font);  

93
  

94
        // 绘制干扰线  

95
        for (int i = 0; i < lineCount; i++) {  

96
            int xs = getRandomNumber(width);  

97
            int ys = getRandomNumber(height);  

98
            int xe = xs + getRandomNumber(width / 8);  

99
            int ye = ys + getRandomNumber(height / 8);  

100
            g.setColor(getRandomColor());  

101
            g.drawLine(xs, ys, xe, ye);  

102
        }  

103
  

104
        

105
        StringBuffer randomCode = new StringBuffer();  

106
        

107
//        int x = 5;

108
        // 随机产生验证码字符  

109
        for (int i = 0; i < codeCount; i++) {

110
            int h = height-8;

111
            int w = (i + 1) * codeX+heightRandom.nextInt(4);

112
            String strRand = String.valueOf(codeSequence[random  

113
                    .nextInt(codeSequence.length)]);  

114
            // 设置字体颜色  

115
            g.setColor(getRandomColor());  

116
117
            int degree = new Random().nextInt() % 10;

118
            g.rotate(degree * Math.PI / 180,(w+codeX-5)/2, (h+fontHeight)/2);

119
            // 设置字体位置  

120
            g.drawString(strRand, w, h );  //getRandomNumber(height / 2) + 25

121
            g.rotate(-degree * Math.PI / 150, (w+codeX-5)/2, (h+fontHeight)/2);

122
            randomCode.append(strRand);  

123
        }  

124
        code = randomCode.toString();  

125
    }  

126
  

127
    /** 获取随机颜色 */  

128
    private Color getRandomColor() {  

129
        int r = getRandomNumber(225);  

130
        int g = getRandomNumber(225);  

131
        int b = getRandomNumber(225);  

132
        return new Color(r, g, b);  

133
    }

134
  

135
    /** 获取随机数 */  

136
    private int getRandomNumber(int number) {  

137
        return random.nextInt(number);  

138
    }  

139
  

140
    public void write(String path) throws IOException {  

141
        OutputStream sos = new FileOutputStream(path);  

142
        this.write(sos);  

143
    }  

144
  

145
    public void write(OutputStream sos) throws IOException {  

146
//         ImageIO.write(buffImg, "png", sos);

147
        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(sos);

148
        encoder.encode(buffImg);

149
        sos.close();  

150
    }  

151
  

152
    public BufferedImage getBuffImg() {  

153
        return buffImg;  

154
    }  

155
  

156
    public String getCode() {  

157
        return code;  

158
    }  

159
  

160
    /** 字体样式类 */  

161
    class ImgFontByte {

162
        public Font getFont(int fontHeight) {  

163
            return new Font("Arial", Font.PLAIN, fontHeight);

164
        }  

165
    }  

166
    

167
    

168
}

169

  • 使用
1
public void scaptcha(){

2
        HttpServletResponse response = ServletActionContext.getResponse();

3
        response.reset();

4
        // 设置响应的类型格式为图片格式  

5
        response.setContentType("image/jpeg");  

6
        // 禁止图像缓存。  

7
        response.setHeader("Pragma", "no-cache");  

8
        response.setHeader("Cache-Control", "no-cache");  

9
        response.setDateHeader("Expires", 0);  

10
        ValidateCode instance = new ValidateCode();

11
        CookieUtil.setCookie(response, "scaptcha", instance.getCode().toUpperCase(), null, -1);

12
        try {

13
            instance.write(response.getOutputStream());

14
        } catch (IOException e) {

15
            e.printStackTrace();

16
        }

17
    }

在使用ImageIO.write时,发现在Linux平台上,会出现异常:

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

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

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

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

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

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

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

12
13
 ... 34 more

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

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

查看日志,发现是由找不到文件引起

1
Java.nio.file.NoSuchFileException: xxx.../temp/imageio4138671232726624650.tmp

  • 主要原因如下:

在使用ImageIO进行图片写操作时,默认会使用缓存目录:${tomcat}/temp,在此缓存目录会生成缓存文件imageio4138671232726624650.tmp(这一串数字应该是当前时间戳,临时文件名),有些生产环境的tomcat,会将temp目录删除,因此报错

  • 4种解决方法如下:
  1. 在tomcat下新建temp目录;
  2. 与方法1相似,通过ImageIO.setCacheDirectory(cacheDirectory);设置任意的、存在的缓存目录
  3. ImageIO默认是使用缓存目录,可以通过ImageIO.setUseCache(false)来设置,更改缓存策略,不使用文件目录缓存,使用内存缓存
  4. 不使用ImageIO,换成其它JDK方法
1
ImageIO.write(bi, "jpg", baos);

2
换成:

3
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(response.getOutputStream()); 

4
encoder.encode(image);

javax异常: javax.imageio.IIOException: Can't create output stream解决方法相关推荐

  1. 计算机开启时提示键盘错误,电脑开机出现异常提示keyboard not found的故障原因及解决方法_电脑故障...

    电脑开机后屏幕显示keyboard not found. press f2 to continue .f1 to setup,具体问题现象如下所示: 故障原因分析: 出现这样的情况大多都是电脑在开机的 ...

  2. vs变量监视提示-VAR-CREATE: UNABLE TO CREATE VARIABLE OBJECT解决方法

    vs变量监视提示-VAR-CREATE: UNABLE TO CREATE VARIABLE OBJECT解决方法 参考文章: (1)vs变量监视提示-VAR-CREATE: UNABLE TO CR ...

  3. 网络异常无法连接远程服务器,《Chess Rush》网络异常进不去怎么回事 无法连接服务器解决方法...

    导 读 Chess Rush突然弹出网络异常无法连接服务器要怎么处理?很多玩家都遇到登录不上游戏的情况,遇到这种问题怎么办?这款游戏海外已经开始下载,由于玩家人数多出现了不少的问题,下面帮大家解决网络 ...

  4. U3d引擎崩溃、异常、警告、BUG与提示总结及解决方法

    此贴会持续更新,都是项目中常会遇到的问题,总结成贴,提醒自己和方便日后检查,也能帮到有需要的同学. 若各位有啥好BUG好异常好警告好崩溃可以分享的话,请多多指教.xuzhiping7#qq.com. ...

  5. jmeter 运行接口报javax.net.ssl.SSLException: Unrecognized SSL message, plaintext connection的解决方法

    今天上午,一位小伙伴(jmeter初学者)在自己抓包后,将接口放到jmeter中,进行接口测试时,出现这样的报错: javax.net.ssl.SSLException: Unrecognized S ...

  6. mysql导入数据io异常_mysql 数据同步 出现Slave_IO_Running:No问题的解决方法小结

    mysql replication 中slave机器上有两个关键的进程,死一个都不行,一个是slave_sql_running,一个是Slave_IO_Running,一个负责与主机的io通信,一个负 ...

  7. 深度deepin20打印失败“Can’t create temporary file”解决方法

    深度20beta下,USB连接HP打印机,自动识别成功,但打印时提示"Can't create temporary file",目测是权限问题. 1.检查权限 getfacl /v ...

  8. SQL Developer Unable to create an instance ...解决方法

    下载解压了Oracle SQL Developer工具,运行时,启动不了,报错信息如下: --------------------------- Unable to create an instanc ...

  9. java 非法操作异常_电脑提示非法操作怎么办 电脑系统故障解决方法【详解】

    电脑提示非法操作怎么办? 在电脑操作中,出现"非法操作"提示的几率比蓝屏现象要多出一筹.造成"非法操作"的原因主要出自软件.当一个程序访问其内存地址空间之外的内 ...

最新文章

  1. MySQL/phpmyadmin问题解决手记:#2002 – 服务器没有响应 (或者本地 MySQL 服务器的套接字没有正确配置)
  2. Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory
  3. 蔚来ES8停车场蛇形走位 连撞数车 官方回应:未证明是车辆失控
  4. awk if 不包含_linux三剑客之awk
  5. 程序员的技术负债怎么还?
  6. 哈萨比斯首次解读AlphaZero竟被当场diss,他起身当面回击说…
  7. ubuntu安装Nvidia-docker2详细步骤
  8. 输出IMG格式SAR图像——Img格式图像文件概述
  9. c语言c98和c99,c99和c98的差异
  10. 如何清理和删除 Docker 镜像
  11. 【GDOI模拟】屏保
  12. H264编码格式--图文解释
  13. 「Mac小技巧」教你如何解决WiFi的国家地区代码冲突
  14. comsol积分函数_空间与时间的积分方法概述
  15. Ghostexp.exe
  16. 【平衡小车制作】(四)陀螺仪MPU6050(超详解)
  17. python爬取千图网_python 爬取 花瓣网图片,千图网图片
  18. DBMS_AUDIT_MGMT.FLUSH_UNIFIED_AUDIT_TRAIL过程
  19. IOS 企业级苹果开发者账号申请流程
  20. SQL报错及解决方法(随缘更新)

热门文章

  1. GHOST使用教程图解
  2. 产品读书《怪诞行为学》
  3. 对自己的些许期盼!!!
  4. 【路由器】TP Link TL-WR702N 迷你路由器为何无法进入管理后台
  5. workbook需要引入的包_解决Maven引用POI的依赖,XSSFWorkbook依旧无法使用的问题
  6. 【web搜索】学习笔记-层次汇合聚类HAC算法
  7. 量化投资:用Python实现金融数据的获取与整理
  8. 山东省谷歌地球高程DEM等高线下载
  9. 外边距塌陷问题及其对策
  10. mysql varchar 单引号_char、varchar数据类型值在使用时可以要用单引号或双引号括起来。...