1

I'm trying to draw some text on some plain color background, and I'm getting some artifacts around the text. Is there a way to get clean writing?

    final BufferedImage image = new BufferedImage(400, 400,
            BufferedImage.TYPE_INT_RGB);

    Graphics2D g2d = (Graphics2D) image.getGraphics();
    g2d.setColor(Color.BLUE);
    g2d.fillRect(0,0, image.getWidth(), image.getHeight());
    Font font = new Font ("Verdana", Font.PLAIN, 40);

    AffineTransform affinetransform = new AffineTransform();
    FontRenderContext frc = new FontRenderContext(affinetransform, true, true);

    TextLayout layout = new TextLayout("Hello World!", font, frc);
    g2d.setColor(Color.WHITE);
    layout.draw(g2d, 100, 100);

    ImageIO.write(image, "jpg", new File("testDirtyText.jpg"));

It's producing some artifacts as shown here: enter image description here

Any advice around any other aspect of this would be appreciated as well.

Thanks!

undetected
  • 474
  • 3
  • 12
  • 2
    Err, what artifacts; sorry, but I only see a blue rectangle with some white text; and nothing that looks "out of order"?! – GhostCat Dec 30 '16 at 19:56
  • The artifacts are just around the edges of the text. It's because of JPEG compression quality issues. @Boann pointed me in the right direction. – undetected Dec 30 '16 at 21:46

1 Answers1

3

I'm not quite sure whether you're referring to aliasing artifacts or JPEG compression artifacts. To fix the former, add:

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

See https://docs.oracle.com/javase/8/docs/api/java/awt/RenderingHints.html for more rendering options.

To fix the latter, save as a PNG instead:

ImageIO.write(image, "png", new File("test.png"));

Or if you really need a JPEG, see this Q&A about setting the JPEG quality level.

Boann
  • 48,794
  • 16
  • 117
  • 146
  • Thanks Boann! It turned out to be the JPEG compression level. I did a separate search on how to set it and ended up in the same link you sent (didn't see the link at first). I thought I already tried it with PNG before, but it looks like I did the PNG before I did the solid color block, so I didn't see the PNG vs JPEG issue then. Setting the compression quality to 90% fixed the issue. – undetected Dec 30 '16 at 21:44