package eofficialsite.utils
import org.apache.commons.lang.RandomStringUtils
import java.awt.Color
import java.awt.Font
import java.awt.Graphics2D
import java.awt.RenderingHints
import java.awt.geom.Rectangle2D
import java.awt.image.BufferedImage
class CaptchaTools {
private final static String CHAR_SET = "abcdefghijkmnpqrstuvwxyABCDEFGHIJKLMNPQRSTUVWXYZ23456789"
private static final int RANDOM_STR_LENGTH = 6
static def newCaptcha() {
final int height = 150
final int width = 200
final int fontSize = 30
final int bottomPadding = 16
final int lineSpacing = 10
// Generate the CAPTCHA solution
String captchaSolution = generateRandomString()
System.setProperty("java.awt.headless", "true")
BufferedImage captchaImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB)
Font font = new Font("Serif", Font.BOLD, fontSize)
Graphics2D g2d = createGraphic(captchaImage, font)
Rectangle2D fontRect = font.getStringBounds(captchaSolution, g2d.fontRenderContext)
// Create a graphic "space" pixels wider and taller than the the font
captchaImage = new BufferedImage((int) fontRect.width + bottomPadding, (int) fontRect.height + bottomPadding, BufferedImage.TYPE_INT_RGB)
g2d = createGraphic(captchaImage, font)
// Draw the background
g2d.color = Color.WHITE
g2d.fillRect(0, 0, width, height)
// Draw the lines
g2d.color = Color.GRAY
int y1 = lineSpacing
int x2 = lineSpacing
int x1 = 0
int y2 = 0
while (x1 < width || x2 < width || y1 < height || y2 < height) {
g2d.drawLine(x1, y1, x2, y2)
if (y1 < height) {
x1 = 0
y1 += lineSpacing
} else if (x1 < width) {
y1 = height
x1 += lineSpacing
} else {
x1 = width
y1 = height
}
if (x2 < width) {
y2 = 0
x2 += lineSpacing
} else if (y2 < height) {
x2 = width
y2 += lineSpacing
} else {
y2 = height
x2 = width
}
}
// Draw the String
g2d.color = Color.BLACK
g2d.drawString(captchaSolution, (int) (bottomPadding / 2), (int) (bottomPadding / 4) + (int) fontRect.height)
return [value: captchaSolution, image: captchaImage]
}
private static Graphics2D createGraphic(BufferedImage image, Font font) {
Graphics2D g2d = image.createGraphics()
g2d.font = font
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
g2d
}
static String generateRandomString(int length = RANDOM_STR_LENGTH){
return RandomStringUtils.random(length, CHAR_SET.toCharArray())
}
}
上面的这个类是生成验证码的工具类,调用方式如下:
def captcha = CaptchaTools.newCaptcha()
ImageIO.write(captcha.image, "PNG", response.outputStream)
如果需要图片为base64位的,那么采用下面的方式:
def captcha = CaptchaTools.newCaptcha()
ByteArrayOutputStream outputStream = new ByteArrayOutputStream()
ImageIO.write(captcha.image, "PNG", outputStream)
def base64Img = new BASE64Encoder().encode(outputStream.toByteArray())
render base64Img