|
| 1 | +package com.shy.day17; |
| 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.FileOutputStream; |
| 8 | +import java.io.IOException; |
| 9 | +import java.io.OutputStream; |
| 10 | +import java.util.Random; |
| 11 | + |
| 12 | +/** |
| 13 | + * @ClassName RandomCode |
| 14 | + * @Author shy |
| 15 | + * @deprecated 随机字符串验证码 |
| 16 | + * @Date 2020/11/5 |
| 17 | + **/ |
| 18 | +public class RandomCode { |
| 19 | + private static final int LENGTH = 4; |
| 20 | + private static final int BOUNDS = 4; |
| 21 | + |
| 22 | + public static void main(String[] args) throws IOException { |
| 23 | + Random random = new Random(); |
| 24 | + //指定图片大小和类型 |
| 25 | + BufferedImage bufferedImage = new BufferedImage(120, 40, BufferedImage.TYPE_INT_RGB); |
| 26 | + //获取画笔 |
| 27 | + Graphics graphics = bufferedImage.getGraphics(); |
| 28 | + //获取字体 |
| 29 | + Font font = new Font("方正华隶简体", Font.BOLD, 20); |
| 30 | + graphics.setFont(font); |
| 31 | + graphics.setColor(Color.WHITE); |
| 32 | + //开始绘制 |
| 33 | + graphics.fillRect(0, 0, 120, 40); |
| 34 | + String s = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdfghijklmnopqrstuvwxyz123456789"; |
| 35 | + char[] chs = s.toCharArray(); |
| 36 | + StringBuilder string = new StringBuilder(); |
| 37 | + for (int i = 0; i < LENGTH; i++) { |
| 38 | + char ch = chs[random.nextInt(60)]; |
| 39 | + string.append(ch); |
| 40 | + } |
| 41 | + //生成随机验证码 |
| 42 | + graphics.setColor(Color.BLACK); |
| 43 | + graphics.drawString(string.toString(), 40 ,28); |
| 44 | + //生成干扰线 |
| 45 | + for (int i = 0; i < BOUNDS; i++) { |
| 46 | + //随机颜色 |
| 47 | + int redRandom = random.nextInt(256); |
| 48 | + int greenRandom = random.nextInt(256); |
| 49 | + int blueRandom = random.nextInt(256); |
| 50 | + //随机坐标 |
| 51 | + int x1 = random.nextInt(120); |
| 52 | + int y1 = random.nextInt(120); |
| 53 | + int x2 = random.nextInt(120); |
| 54 | + int y2 = random.nextInt(120); |
| 55 | + Color color = new Color(redRandom, greenRandom, blueRandom); |
| 56 | + graphics.setColor(color); |
| 57 | + graphics.drawLine(x1,y1,x2,y2); |
| 58 | + } |
| 59 | + //输出图片,并指定文件路径,自己注意修改 |
| 60 | + File file = new File("E:\\code.jpg"); |
| 61 | + //获取输出流 |
| 62 | + OutputStream outputStream = new FileOutputStream(file); |
| 63 | + //将图片从缓冲区通过字节写到文件 |
| 64 | + ImageIO.write(bufferedImage,"jpg",outputStream); |
| 65 | + //关闭输出流 |
| 66 | + outputStream.close(); |
| 67 | + } |
| 68 | +} |
0 commit comments