验证码图片转字符串

为什么?

因为之前一个项目,安卓那边说只能处理JSON,别的都不行。。。(后来问过他人,明明可以处理其他的~~)

当时因为赶进度,所以直接缓存了图片(囧),然后将图片地址发出去。

过后想了下完全可以转成字符串发送过去。

方法如下:

验证码图片

public BufferedImage getImage() throws IOException{
    int width = 60;
    int height = 32;
    //create the image
    BufferedImage image =  new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    Graphics g = image.getGraphics();

    // set the background color
    g.setColor(new Color(0xDCDCDC));
    g.fillRect(0, 0, width, height);
    // draw the border
    g.setColor(Color.black);
    g.drawRect(0, 0, width - 1, height - 1);
    // create a random instance to generate the codes
    Random rdm = new Random();
    String hash1 = Integer.toHexString(rdm.nextInt());
    // make some confusion
    for(int i = 0; i < 50; i++){
        int x = rdm.nextInt(width);
        int y = rdm.nextInt(height);
        g.drawOval(x, y, 0, 0);
    }
    // generate a random code
    String capstr = hash1.substring(0, 4);

    g.setColor(new Color(0, 100, 0));
    g.setFont(new Font("Candara", Font.BOLD, 24));
    g.drawString(capstr, 8, 24);
    g.dispose();

    return image;
}

JSP中直接输出

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

转成字符串的工具方法

public static byte[] object2byteArray(Object object){
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    ObjectOutputStream objectOutputStream = null;
    byte[] bytes = null;

    try{
        objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
        objectOutputStream.writeObject(object);
        bytes = byteArrayOutputStream.toByteArray();

        byteArrayOutputStream.close();
        objectOutputStream.close();
        return bytes;
    } catch(IOException e){
        e.printStackTrace();
    }
    return null;
}

测试方法

@Test
public void run() throws IOException{
    byte[] bytes = object2byteArray(getImage());
    String str = Base64.getEncoder().encodeToString(bytes);
    System.out.println(str);
}

但是,行不通!!!因为BufferedImage没有实现序列化接口,囧囧有神~

解决办法

/**
 * 这个类,纯粹为了实现序列化接口!
 */
public class MyBufferedImage extends BufferedImage implements Serializable {
    public MyBufferedImage(int width, int height, int imageType){
        super(width, height, imageType);
    }

    public MyBufferedImage(int width, int height, int imageType, IndexColorModel cm){
        super(width, height, imageType, cm);
    }

    public MyBufferedImage(ColorModel cm, WritableRaster raster, boolean isRasterPremultiplied, Hashtable<?, ?> properties){
        super(cm, raster, isRasterPremultiplied, properties);
    }
}

然后

public MyBufferedImage getImage() throws IOException{
    int width = 60;
    int height = 32;
    //create the image
    MyBufferedImage image =  new MyBufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    Graphics g = image.getGraphics();

    // set the background color
    g.setColor(new Color(0xDCDCDC));
    g.fillRect(0, 0, width, height);
    // draw the border
    g.setColor(Color.black);
    g.drawRect(0, 0, width - 1, height - 1);
    // create a random instance to generate the codes
    Random rdm = new Random();
    String hash1 = Integer.toHexString(rdm.nextInt());
    // make some confusion
    for(int i = 0; i < 50; i++){
        int x = rdm.nextInt(width);
        int y = rdm.nextInt(height);
        g.drawOval(x, y, 0, 0);
    }
    // generate a random code
    String capstr = hash1.substring(0, 4);

    g.setColor(new Color(0, 100, 0));
    g.setFont(new Font("Candara", Font.BOLD, 24));
    g.drawString(capstr, 8, 24);
    g.dispose();

    return image;
}

现在再执行测试就OK啦。

时间: 2024-08-26 23:50:43

验证码图片转字符串的相关文章

用python生成验证码图片

除了配置好的python环境外,还需要配有python中的PIL库,这是python中专门用来处理图片的库.用传统的pip install 方法或者下载源码 python setup.py install 方法安装该库,很可能会报错(视运行环境不同).可以采用以下方法: 1.下载安装包URL:http://www.pythonware.com/products/pil/index.htm,要下载支持全平台的. 2.解压缩: tar –zxv –f Imaging-1.1.7.tar.gz 3.进

用动态网页技术PHP生成验证码图片的源代码

文件a.php <? //checkNum.php session_start(); function random($len) { $srcstr="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; mt_srand(); $strs=""; for($i=0;$i<$len;$i++){ $strs.=$srcstr[mt_rand(0,35)]; } return strtoupper($strs); } $str=ra

C#实现登陆验证码图片的动态生成

public ActionResult SecurityCode() { string oldcode = TempData["SecurityCode"] as string; string code = CreateRandomCode(4); //验证码的字符为4个 TempData["SecurityCode"] = code; //验证码存放在TempData中 return File(CreateValidateGraphic(code), "

java生成验证码图片

public class AuthImg extends HttpServlet { /** * */ private static final long serialVersionUID = 4975974534946437434L; // 设置图形验证码字符串的字体和大小 private Font mFont = new Font("微软雅黑", Font.ITALIC, 18); private Random random = new Random(); public void

Struts2 验证码图片实例

本文分三个步骤介绍验证码图片生成以及与Struts2结合使用. Step 1.随机验证码 一步一步来,要生成验证码图片,首先要有验证码,然后才能在画在图片上.为了能够灵活控制验证码,特别编写了SecurityCode类,它向外提 供随机字符串.并且可以控制字符串的长度和难度.SecurityCode类中提供的验证码分三个难度,易(全数字).中(数字+小写英文).难(数字+ 大小写英文).难度使用枚举SecurityCodeLevle表示,避免使用1.2.3这样没有明确意义的数字来区分. 同时,还

php验证码图片里的点点与线线,和数据库部分封装

? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 <?php //定义常量 define("HOST","127.0.0.1"); define("USER","root"); define("PWD","

第二百七十节,Tornado框架-生成验证码图片,以及验证码结合Session验证

Tornado框架-生成验证码图片,以及验证码结合Session验证 第一.生成验证码图片  生成验证码图片需要两个必须模块 1.python自带的random(随机模块) 2.Pillow()图像处理模块里的PIL(图像库),为第三方模块,需要安装 封装验证码图片生成插件py 在封装文件里先导入random(随机模块),和Pillow()图像处理模块里的所需py文件 封装验证码图片生成插件功能,调用后返回验证码图片,和字符串类型验证码,两个返回值 注意:验证码需要一个字体文件,这个字体文件必须

Trident内核中取验证码图片的几种方法

程序中用了IE的内核,想取出网站中的验证码图片,单独显示出来,调研了以下几路方法 1.枚举所有缓存文件,进行处理,找到想要的,核心代码 if (0)//这段代码可以枚举所有缓存资源,然后对应做处理 { LPINTERNET_CACHE_ENTRY_INFO lpCacheEntry = NULL; HANDLE hCacheDir = NULL; DWORD dwTrySize, dwEntrySize = 4096; DWORD dwError = ERROR_INSUFFICIENT_BUF

Python 生成4位验证码图片

import randomimport stringfrom PIL import Image,ImageDraw,ImageFont,ImageFilter # 字体的位置font_path = "/Library/Fonts/Arial.ttf"# 验证码的位数number = 4# 生成图片的大小size = (100,30)# 图片背景颜色-白色bgcolor = (255,255,255)# 验证码字体颜色--蓝色fontcolor = (0,0,255)# 干扰线的颜色--