title: Java 1.6 Graphics2D: Rendering text into a box
body: <p>I am looking for an easy way to render a String into a rectangular box within a JPG whereas line breaks should happen automatically for that text box.</p>
  
  <p>Is this possible with <code>Graphics2D</code> ?</p>
  
  <p>Rendering a string on a single line is easy, the following code snippet uses Antialiasing as well as a good JPG output compression quality:</p>
  
  <pre><code>BufferedImage img = ImageIO.read(new File(".../input.jpg"));
  int width = img.getWidth();
  int height = img.getHeight();
  
  Color zgColor = new Color(0xAB,0x3C,0x2E);
  Color grey = new Color(0xCC,0xCC,0xCC);
  
  BufferedImage bufferedImage = new BufferedImage(width, height, img.getType());
  Graphics2D g = bufferedImage.createGraphics();
  g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
  // draw graphics
  g.drawImage(img, 0, 0, null);
  g.setColor(zgColor);
  int y = 900;
  int x = 50;
  g.setFont(new Font("Arial", Font.BOLD, 80));
  g.drawString("Demo Text", x, y);
  
  y+=80;
  g.setColor(Color.WHITE);
  g.setFont(new Font("Arial", Font.BOLD, 60));
  g.drawString("Some other text a bit below", x, y);
  
  y+=400;
  g.setFont(new Font("Arial", Font.BOLD, 30));
  g.setColor(Color.WHITE);
  g.drawString("AND THIS WOULD BE THE TEXT I'D LIKE TO FIT INTO A BOX WITH AUTOMATIC LINE BREAKS", x, y);
  
  g.dispose();
  
  // Save as high quality JPEG
  File targetFile = new File(".......result.jpg");
  //ImageIO.write(bufferedImage, "jpg", targetFile); // this would give bad quality!
  
  Iterator iter = ImageIO.getImageWritersByFormatName("jpeg");
  ImageWriter writer = (ImageWriter)iter.next();
  ImageWriteParam iwp = writer.getDefaultWriteParam();
  iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
  iwp.setCompressionQuality(1); // best quality
  FileImageOutputStream output = new FileImageOutputStream(targetFile);
  writer.setOutput(output);
  IIOImage image = new IIOImage(bufferedImage, null, null);
  writer.write(null, image, iwp);
  writer.dispose();            
  System.out.println("Done.");
  </code></pre>