简体   繁体   中英

Wrong colors in JLabel when using HTML string

I'm trying to use HTML styling in a JLabel and convert the BufferedImage to jpg. However the colors are quite different than what I expect.

Here is the code:

val html = "<html><body style='width: 400px; padding: 5px; margin:0; color:#000;'>" + "<h1>teststring1</h1>" + key + " <h2>teststring</h2><body></html>"
val textLabe = new JLabel(html)
textLabe.setSize(textLabe.getPreferredSize)
val d: Dimension = textLabe.getPreferredSize
val bi: BufferedImage = new BufferedImage(d.width, d.height, BufferedImage.TYPE_INT_ARGB)
val g = bi.createGraphics
textLabe.paint(g)

val a = new ByteArrayOutputStream()
ImageIO.write(bi, "jpg", a)

As you can see the text color is not black and the background is black instead of white. I tried to set setForeground(Colors.white), setBackground(Colors.white) and setOpaque(true) but the background color turn into pink in this case.

在此输入图像描述

How can I fix this problem?

the background color turn into pink in this case.

Not sure what JDK/JRE you are using, but there seems to be something wrong with the JPEGImageWriter , particularly the way it handles alpha.

Try using a BufferedImage of TYPE_INT_RGB or TYPE_3BYTE_RGB instead of TYPE_INT_ARGB as a workaround, or alternatively write the image as a PNG.

Then, use setOpaque(true) to make sure the background is painted, and setBackground(Color.WHITE) to set the correct background color. You should now have a correctly colored output image.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM