Question

I'm in the process of making a captcha in Java but I'm having trouble improving the text quality the "drawString" method generates on top of my image.

Example of the text quality:

You can actually see the horrible edges on the text.

Java code:

File file = new File("C:\\captcha.png");
File file2 = new File("C:\\captcha2.png");
File fontfile = new File("C:\\xerox.ttf");
BufferedImage bfimage = ImageIO.read(file);
Graphics2D g = bfimage.createGraphics();
Font myfont = Font.createFont(Font.PLAIN, fontfile);
myfont = myfont.deriveFont(50f);
g.setFont(myfont);
g.setColor(Color.black);
AffineTransform att = new AffineTransform();
g.translate(100, 50);
att.rotate(Math.toRadians(15), 100, 50);
g.setTransform(att);
g.drawString("12345", 100, 50);
RenderedImage rimg = bfimage;
ImageIO.write(rimg, "PNG", file2);

Example of same font used in php, but here the quality is A LOT better with smooth edges:

How do I improve the text quality generated by the "drawString" method in Java?

Was it helpful?

Solution

Graphics and Graphics2D provide a rendering hint framework that allows you to configure some parts of the rendering of a component. Use an antialiasing rendering hint:

g2d.setRenderingHint( RenderingHints.KEY_TEXT_ANTIALIASING, 
RenderingHints.VALUE_TEXT_ANTIALIAS_DEFAULT);

and you should get antialiased text on your captcha.

http://docs.oracle.com/javase/6/docs/api/java/awt/RenderingHints.html for reference

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top