ele-admin / EasyCaptcha

Java图形验证码,支持gif、中文、算术等类型,可用于Java Web、JavaSE等项目。
Apache License 2.0
112 stars 25 forks source link

如何让背景透明色 #46

Open jiashu1024 opened 1 year ago

jiashu1024 commented 1 year ago

原来白色和网站风格不太搭

jiashu1024 commented 1 year ago
package com.zjs.feishubot.config;

import com.wf.captcha.SpecCaptcha;
import org.springframework.stereotype.Component;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
@Component
public class TransparentCaptcha extends SpecCaptcha {

  public TransparentCaptcha() {
    super();
  }

  public TransparentCaptcha(int width, int height) {
    super(width, height);
  }

  public TransparentCaptcha(int width, int height, int len) {
    super(width, height, len);
  }

  public TransparentCaptcha(int width, int height, int len, Font font) {
    super(width, height, len, font);
  }

  @Override
  public boolean out(OutputStream out) {
    return graphicsImage(textChar(), out);
  }

  private boolean graphicsImage(char[] strs, OutputStream out) {
    try {
      BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
      Graphics2D g2d = (Graphics2D) bi.getGraphics();
      // 填充背景
//      g2d.setColor(Color.WHITE);
      g2d.setColor(new Color(255, 255, 255, 0));
      g2d.fillRect(0, 0, width, height);
      // 抗锯齿
      g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
      // 画干扰圆
      drawOval(2, g2d);
      // 画干扰线
      g2d.setStroke(new BasicStroke(2f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL));
      drawBesselLine(1, g2d);
      // 画字符串
      g2d.setFont(getFont());
      FontMetrics fontMetrics = g2d.getFontMetrics();
      int fW = width / strs.length;  // 每一个字符所占的宽度
      int fSp = (fW - (int) fontMetrics.getStringBounds("W", g2d).getWidth()) / 2;  // 字符的左右边距
      for (int i = 0; i < strs.length; i++) {
        g2d.setColor(color());
        int fY = height - ((height - (int) fontMetrics.getStringBounds(String.valueOf(strs[i]), g2d).getHeight()) >> 1);  // 文字的纵坐标
        g2d.drawString(String.valueOf(strs[i]), i * fW + fSp + 3, fY - 3);
      }
      g2d.dispose();
      ImageIO.write(bi, "png", out);
      out.flush();
      return true;
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      try {
        out.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
    return false;
  }
}

重写了普通验证码的方法,实现了更改透明色