Create image from text with unknown number of line

2019-06-08 14:23发布

问题:

I would like to convert a string of text into an image. The issue is, I want the text to wrap if it is wider than the length of the image, and the height of the image to be dynamically sized to perfectly fit the text, so that I know how much space the text takes up.

I'm working in Java and there are several things I have tried:

  • Rendering HTML in a JPanel and saving as a BufferedImage. The problem here was that most of the css I used was ignored by the JPanel and the image was unusable.

  • Using ImageMagick and img4Java. The two big failures with this solution was that I needed the command-line tool installed, which I can't do on our server. The second was that I couldn't easily convert the image to buffered image for use in the rest of the app.

Does anyone know a way to do this in Java?

Thanks!

回答1:

In this example, an arbitrary panel is rendered into a BufferedImage and displayed in an adjacent panel at half-scale. The example uses a grid of labels, but you can use the wrap feature of JTextArea or the geometry supplied by TextLayout, examined here.



回答2:

You might use a label containing HTML for the line-wrap, as shown here.

To get an image of that, see LabelRenderTest.