From f8626e3670734baf06c3274b6cd5d47ac3c5e147 Mon Sep 17 00:00:00 2001 From: hrj Date: Sun, 3 Apr 2022 23:22:45 +0530 Subject: [PATCH] shadow text: adapt text to size dynamically --- src/main/java/lc/captchas/ShadowTextCaptcha.java | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/src/main/java/lc/captchas/ShadowTextCaptcha.java b/src/main/java/lc/captchas/ShadowTextCaptcha.java index 16bbdc1..cdc314f 100644 --- a/src/main/java/lc/captchas/ShadowTextCaptcha.java +++ b/src/main/java/lc/captchas/ShadowTextCaptcha.java @@ -47,14 +47,18 @@ public class ShadowTextCaptcha implements ChallengeProvider { private byte[] shadowText(final int width, final int height, String text) { BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); - Font font = new Font("Arial", Font.ROMAN_BASELINE, 48); + final int fontHeight = (int) (height * 0.5f); + Font font = new Font("Arial", Font.PLAIN, fontHeight); Graphics2D graphics2D = img.createGraphics(); HelperFunctions.setRenderingHints(graphics2D); graphics2D.setPaint(Color.WHITE); graphics2D.fillRect(0, 0, width, height); graphics2D.setPaint(Color.BLACK); graphics2D.setFont(font); - graphics2D.drawString(text, 15, 50); + final var stringWidth = graphics2D.getFontMetrics().stringWidth(text); + final var scaleX = (stringWidth > width) ? width/((double) stringWidth) : 1d; + graphics2D.scale(scaleX, 1d); + graphics2D.drawString(text, 0, fontHeight*1.1f); graphics2D.dispose(); final int kernelSize = (int) Math.ceil((Math.min(width, height) / 50.0)); ConvolveOp op = new ConvolveOp(new Kernel(kernelSize, kernelSize, makeKernel(kernelSize)), ConvolveOp.EDGE_NO_OP, null); @@ -62,8 +66,9 @@ public class ShadowTextCaptcha implements ChallengeProvider { Graphics2D g2d = img2.createGraphics(); HelperFunctions.setRenderingHints(g2d); g2d.setPaint(Color.WHITE); + g2d.scale(scaleX, 1d); g2d.setFont(font); - g2d.drawString(text, 13, 50); + g2d.drawString(text, -kernelSize, fontHeight*1.1f); g2d.dispose(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); try {