shadow text: adapt text to size dynamically

This commit is contained in:
hrj 2022-04-03 23:22:45 +05:30
parent 83b0eb069e
commit f8626e3670

View File

@ -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 {