zoukankan      html  css  js  c++  java
  • 生成图片验证码

     1  package util;
     2  
     3 import javax.imageio.ImageIO;
     4 import java.awt.*;
     5 import java.awt.image.BufferedImage;
     6 import java.io.File;
     7 import java.io.IOException;
     8 import java.util.Random;
     9  
    10 public class image {
    11     public static int[] ran() {
    12         //设置图片宽度和高度
    13         int width = 150;
    14         int height = 60;
    15         //干扰线条数
    16         int lines = 10;
    17 //        验证码数组
    18         int[] random = new int[4];
    19         Random r = new Random();
    20         BufferedImage b = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    21         Graphics g = b.getGraphics();
    22         g.setFont(new Font("宋体", Font.BOLD, 30));
    23         for (int i = 0; i < 4; i++) {
    24             int number = r.nextInt(10);
    25             random[i] = number;
    26             int y = 10+r.nextInt(40);// 10~40范围内的一个整数,作为y坐标
    27             //随机颜色,RGB模式
    28             Color c = new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255));
    29             g.setColor(c);
    30 //            g.drawString("" + a, 5 + i * width / 4, y);
    31             //写验证码
    32             g.drawString(Integer.toString(number), 5 + i * width / 4, y);
    33         }
    34         for (int i = 0; i < lines; i++) {
    35             //设置干扰线颜色
    36             Color c = new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255));
    37             g.setColor(c);
    38             g.drawLine(r.nextInt(width), r.nextInt(height), r.nextInt(width), r.nextInt(height));
    39         }
    40         try {
    41             //清空缓冲
    42             g.dispose();
    43             //向文件中写入
    44             ImageIO.write(b, "jpg", new File("E:\IntelliJ IDEA\mail\web\imagecode\test.jpg"));
    45         } catch (IOException e) {
    46             e.printStackTrace();
    47         }
    48         return random;
    49     }
    50  
    51     //测试
    52     public static void main(String[] args) {
    53         ran();
    54     }
    55 } 
  • 相关阅读:
    Java bytesToHexString 解析
    Redis 启动警告错误解决
    Jackson
    HttpClient和HttpURLConnection的区别
    (HttpURLConnection)强制转化
    由sqlite在手机上的存储位置,引发的onCreate在哪里执行的小结
    Android数据存储五种方式总结
    Android 操作SQLite基本用法
    Android中SQLite应用详解
    android基础
  • 原文地址:https://www.cnblogs.com/EveningWind/p/9838148.html
Copyright © 2011-2022 走看看