Using text attributes for picture in Graphics2D object JAVA - java

I have a weird problem - I'm trying to write a text string over a transparent GIF picture.
I'm using awt Graphics2D object, and for some reason, I cannot affect the way the text looks - its color, its alignment and so on. Every time I use drawString with a string,
it is white and centered left.
Is this a problem with my jre? With GIF format? Or the fact that the picture is transparent?
I tried doing this: (TextAttributes is just some container class I created)
Map<TextAttribute, Object> fontAtts = new Hashtable<TextAttribute, Object>();
fontAtts.put(TextAttribute.RUN_DIRECTION, TextAttribute.RUN_DIRECTION_RTL);
fontAtts.put(TextAttribute.FAMILY, TextAttributes.type);
fontAtts.put(TextAttribute.FOREGROUND, TextAttributes.color);
fontAtts.put(TextAttribute.SIZE, TextAttributes.size);
Font font = new Font(fontAtts);
BufferedImage image = getImage(picturePath, pictureName, format);\\just gives me the buffered image
Graphics2D g2 = image.createGraphics();
//first way:
g2.setFont(font);
g2.drawString("bla blah", 200,150)
//second way
g2.setPaint(TextAttributes.color);
g2.drawString("bla blah", 200,150)
//third way
g2.setColor(Color.RED);
g2.drawString("bla blah", 200,150)
//fourth way
AttributedString x = new AttributedString("blah blah", fontAtts);
g2.drawString(x.getIterator(),200,150)
but nothing works :(

Related

I want to create an jpg image dynamically based on the text input using core java

I am trying to create images at runtime using graphics class. But though I have a string like line 1 \n line 2, I get the text written on the image as a single line.
Can anyone help me on this front with an example?
To remove the line breaks from your string, you can use the following method:
String str = "Line 1\nLine 2";
str.replace(System.getProperty("line.separator"), "");
You can use the BufferedImage class for creating the image:
// Create the target Font and a FontMetrics object for measuring the string's dimensions on the canvas
Font font = new Font("Helvetica", Font.PLAIN, 12);
FontMetrics fm = new Canvas().getFontMetrics(font);
// Create a BufferedImage and obtain the Graphics object
BufferedImage img = new BufferedImage(fm.stringWidth(str), fm.getHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics g = img.getGraphics();
// Draw the string at position (0|0)
g.setColor(Color.black);
g.drawString(str, 0, 0);

Write text on the screen with LWJGL

I want to write text on the screen for my game, for things like fps, random text for items and stuff. How can I write that text?
Is it possible without the Basic Game class? Isn't there a command like this g.drawString("Hello World", 100, 100);?
Update: this answer is now outdated, and does not work at all with the latest versions of LWJGL. Until I update this answer fully, I recommend that you look here: https://jvm-gaming.org/t/lwjgl-stb-bindings/54537
You could use the TrueType fonts feature in the Slick-util library.
Using a common font is easy, just create the font like this:
TrueTypeFont font;
Font awtFont = new Font("Times New Roman", Font.BOLD, 24); //name, style (PLAIN, BOLD, or ITALIC), size
font = new TrueTypeFont(awtFont, false); //base Font, anti-aliasing true/false
If you want to load the font from a .ttf file, it's a little more tricky:
try {
InputStream inputStream = ResourceLoader.getResourceAsStream("myfont.ttf");
Font awtFont = Font.createFont(Font.TRUETYPE_FONT, inputStream);
awtFont = awtFont.deriveFont(24f); // set font size
font = new TrueTypeFont(awtFont, false);
} catch (Exception e) {
e.printStackTrace();
}
After you have successfully created a TrueTypeFont, you can draw it like this:
font.drawString(100, 50, "ABC123", Color.yellow); //x, y, string to draw, color
For more information, you can look at the documentation for TrueTypeFont and java.awt.Font, and the Slick-Util tutorial I got most of this code from.
Try Making a BufferedImage of required size. Then get its Graphics and draw a String. Then Convert it to a ByteBuffer and render it in OpenGL.
String text = "ABCD";
int s = 256; //Take whatever size suits you.
BufferedImage b = new BufferedImage(s, s, BufferedImage.TYPE_4BYTE_ABGR);
Graphics2D g = b.createGraphics();
g.drawString(text, 0, 0);
int co = b.getColorModel().getNumComponents();
byte[] data = new byte[co * s * s];
b.getRaster().getDataElements(0, 0, s, s, data);
ByteBuffer pixels = BufferUtils.createByteBuffer(data.length);
pixels.put(data);
pixels.rewind();
Now pixels contains the required Image data you need to draw.
Use GL11.glTexImage2D() function to draw the byte buffer.

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.

IText - BarcodeQRCode making the background color transparent

I'm trying to set the background color of my QR Code using iText into a transparent background, however it does not work. Shows only white bars and black background.
What i have done so far:
My Code Snippet:
PdfContentByte cb = writer.getDirectContent();
BarcodeQRCode qrcode = new BarcodeQRCode("sample message on qr", 100, 100, null);
java.awt.Image qrImage = qrcode.createAwtImage(Color.WHITE,new Color(0, 0, 0, 0));
Image finalImage = Image.getInstance(writer, qrImage, 1);
finalImage.setAbsolutePosition(positionX, positionY);
cb.addImage(finalImage);
I have already generated my QR code and produced a PDF, however, when using
qrcode.createAwtImage(Color.WHITE,new Color(0, 0, 0, 0));
It does not produce an alpha background, instead it only shows a black background color.
I have also tried:
java.awt.Image qrImage =
qrcode.createAwtImage(Color.WHITE,Color.OPAQUE);
But obviously, my arguments are incorrect.
Help will be most appreciated, i've been working on this for a day now.
I have also tried Graphics, Graphics2g, converting it into BufferedImage.
Changing the assignment of finalImage to the following works:
Image finalImage = Image.getInstance(qrImage, null)
I don't know why using the getInstance method that takes a PdfWriter as first argument ruins the transparency, though...
I would solve this problem like this:
BarcodeQRCode qrcode = new BarcodeQRCode("sample message on qr", 100, 100, null);
Image image = qrcode.getImage();
Image mask = qrcode.getImage();
mask.makeMask();
image.setImageMask(mask);
document.add(image);
There may be an AWT solution too, but I'm more familiar with native PDF solutions than with using an AWT workaround.

How can I generate text image same as the JLabel label?

I would like to generate text image same as the JLabel label without displaying JLabel.
I tried same Font, same drawing method.
But generated image is not same as JLabel.
My sourcecode is below.
* 'super.paintComponent(g)' has been commented out for clarity that it is the same way. Output image is same.
* Below drawing by 'View.paint' method, but I'm tried 'SwingUtilities2.drawString' too. Two results are the same.
/* Label */
JLabel label = new JLabel(text) {
#Override
public void paintComponent(Graphics g) {
//super.paintComponent(g);
View v = BasicHTML.createHTMLView(this, getText());
v.paint(g, new Rectangle(0, 0, getWidth(), getFontMetrics(
getFont()).getAscent()));
}
};
label.setFont(new Font("Consolas", Font.PLAIN, 13));
/* Image */
FontMetrics fm = label.getFontMetrics(font);
BufferedImage image = new BufferedImage(fm.stringWidth(text),
fm.getHeight(), BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = image.createGraphics();
g2d.setFont(label.getFont());
// Clear background.
g2d.setPaint(label.getBackground());
g2d.fillRect(0, 0, image.getWidth(), image.getHeight());
// Draw string.
g2d.setClip(new Rectangle(0, 0, image.getWidth(), image.getHeight()));
View v = BasicHTML.createHTMLView(label, text);
v.paint(g2d, new Rectangle(0, 0, image.getWidth(),
g2d.getFontMetrics().getAscent()));
// ... output image to file ...
Result image is following.
[JLabel]
[Generated image]
Generated image is slightly thin-faced, as compared to JLabel's capture.
How can I generate text image same as the JLabel label?
Thank you for your consideration.
I'm not sure, but you might need to create a compatible buffered image (compatible to the display)
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice gs = ge.getDefaultScreenDevice();
GraphicsConfiguration gc = gs.getDefaultConfiguration();
// Create an image that does not support transparency
BufferedImage bimage = gc.createCompatibleImage(100, 100, Transparency.OPAQUE);
This will at least get you on a close with the graphics been used to render to the screen
You might also like to pay around with the rendering quality as well
Kleopatra did a post on a similar question awhile ago, you might to try and hunt it down
Why do you use BasicHTML.createView if you want to have the same as JLabel?
You could use the JLabel directly (if you only want the text and not the background, set opaque to false and the border to null)
or you can use g2d.drawString()

Categories

Resources