Bold text on image - java

I want to append bold text on image, only selected text should be bold.
String word="This is dummy text, this should be BOLD"
final BufferedImage image = ImageIO.read(new File(Background));
Graphics g = image.getGraphics();
g.drawString(word, curX, curY);
g.dispose();
ImageIO.write(image, "bmp", new File("output.bmp"));

You want to use an AttributedString and pass its iterator to drawString
static String Background = "input.png";
static int curX = 10;
static int curY = 50;
public static void main(String[] args) throws Exception {
AttributedString word= new AttributedString("This is text. This should be BOLD");
word.addAttribute(TextAttribute.FONT, new Font("TimesRoman", Font.PLAIN, 18));
word.addAttribute(TextAttribute.FOREGROUND, Color.BLACK);
// Sets the font to bold from index 29 (inclusive)
// to index 33 (exclusive)
word.addAttribute(TextAttribute.FONT, new Font("TimesRoman", Font.BOLD, 18), 29,33);
word.addAttribute(TextAttribute.FOREGROUND, Color.BLUE, 29,33);
final BufferedImage image = ImageIO.read(new File(Background));
Graphics g = image.getGraphics();
g.drawString(word.getIterator(), curX, curY);
g.dispose();
ImageIO.write(image, "png", new File("output.png"));
}
output.png:

You can set a Font on the Graphics object before you draw the String like this:
Font test = new Font("Arial",Font.BOLD,20);
g.setFont(test);
If you only want one word bold you'll have to call drawString twice, and set the font to bold only the second time.

Maybe this one will help - curX,curY should be updated after the first drawString probably, otherwise it will look quite nasty. :)
String word="This is text, this should be ";
final BufferedImage image = ImageIO.read(new File(Background));
Graphics g = image.getGraphics();
g.drawString(word, curX, curY);
Font f = new Font("TimesRoman", Font.Bold, 72);
g.setFont(f);
String word="BOLD";
g.drawString(word, curX, curY);
g.dispose();
ImageIO.write(image, "bmp", new File("output.bmp"));

Related

JLabel: Squish text if it doesn't fit

I have JLabels in a constrained space (JTable) and when the text inside the label is too long, it's truncated. Is there a way to make the text fit in the allotted space by only horizontal squishing?
See the upper Jlabel in these examples:
The text is HTML formatted so I can't just drawstring on a custom JPanel component myself. There's no icon.
Since I've solved this question while typing it, in accordance with meta I'll share the answer.
I set this as the UI for the JLabel:
It renders the text to an off-screen image, then resizes that image to the JLabel's proportions.
[Edit] This doesn't work correctly with transparent labels or labels with empty HTML text.
// Copied and modified from BasicLabelUI
private static class SquishLabelUI extends BasicLabelUI {
private final Rectangle paintIconR = new Rectangle();
private final Rectangle paintTextR = new Rectangle();
private String layout(JLabel label, FontMetrics fm, int width, int height) {
Insets insets = label.getInsets(null);
String text = label.getText();
Rectangle paintViewR = new Rectangle(insets.left,
insets.top,
width - (insets.left + insets.right),
height - (insets.top + insets.bottom));
paintIconR.setBounds(0, 0, 0, 0);
paintTextR.setBounds(0, 0, 0, 0);
return layoutCL(label, fm, text, null, paintViewR, paintIconR, paintTextR);
}
#Override
public void paint(Graphics g, JComponent c) {
JLabel label = (JLabel)c;
layout(label, SwingUtilities2.getFontMetrics(label, g), c.getWidth(), c.getHeight());
View v = (View)c.getClientProperty(BasicHTML.propertyKey);
Dimension size = getPreferredSize(label);
BufferedImage img = label.getGraphicsConfiguration()
.createCompatibleImage(size.width, size.height, TRANSLUCENT);
Graphics2D g2 = img.createGraphics();
try {
g2.setColor(label.getBackground());
g2.setClip(0, 0, size.width, size.height);
g2.fillRect(0, 0, size.width, size.height);
v.paint(g2, new Rectangle(0, 0, size.width, size.height));
int renderWidth = Math.min(size.width, paintTextR.width);
Image img2 = img.getScaledInstance(renderWidth, paintTextR.height, Image.SCALE_SMOOTH);
g.drawImage(img2, paintTextR.x, paintTextR.y, null);
} finally {
g2.dispose();
}
}
}

Java Add span to image background color

i want to add additional space in images, lets call it "span".
My code is:
BufferedImage newImage = new BufferedImage(image2.getWidth(), image2.getHeight()+200, image2.getType());
Graphics g = newImage.getGraphics();
g.setColor(Color.white);
g.fillRect(0,0,image.getWidth(),image.getHeight()+100);
g.drawImage(image, 0, 100, null);
g.setColor(Color.white);
g.dispose();
RenderedImage rendImage = newImage;
String newUrl8006002 = splitUrl[0]+"-800x6002.jpg";
File file = new File(newUrl8006002);
ImageIO.write(rendImage, "jpg", file);
The problem is, that image at the bottom has black background and i expect white (at the top is white).
Do you know what to change to add white background in whole image?
How about this:
static BufferedImage growY(BufferedImage im, int span, Color color)
{
BufferedImage newImage = new BufferedImage(im.getWidth(), im.getHeight()+span, im.getType());
int topSpan = span/2;
int botSpan = span - topSpan;
Graphics g = newImage.getGraphics();
g.setColor(color);
g.fillRect(0, 0, newImage.getWidth(), topSpan);
g.fillRect(0, topSpan+im.getHeight(), newImage.getWidth(), botSpan);
g.drawImage(im, 0, topSpan, null);
g.dispose();
return newImage;
}

Java Swing draw html formatted string

I want to create a String which displays the time in the format: 10h 30min, but the units (h and min) should have a smaller font than the numbers. When using a JLabel, I get this work with a html formatted string with span attributes.
Now I want to add such a String to a custom object and write it with the drawAlignedString method. But, here the html passing does not working. The custom object than shows my code and not the formatted String.
Is there a way to get this working or any other solution for drawing Strings with diffrent Substrings?
This is what I've tried:
String time = String.format(
"<html>%d<span style=\"font-family:Arial Unicode MS;font-size:12px;\">h </span> %d<span "
+ "style=\"font-family:Arial Unicode MS;font-size:12px;\">min</span></html>",
absSeconds / 3600, (absSeconds % 3600) / 60);
g2.setFont(this.centerTextFont);
g2.setPaint(this.centerTextColor);
TextUtilities.drawAlignedString(time, g2, (float) area.getCenterX(), (float) area.getCenterY(),
TextAnchor.CENTER);
Once the label is configured, pass the Graphics to the paint method of the label.
import java.awt.*;
import java.awt.image.BufferedImage;
import javax.swing.*;
public class LabelRenderTest {
public static void main(String[] args) {
SwingUtilities.invokeLater( new Runnable() {
public void run() {
String title = "<html><body style='width: 200px; padding: 5px;'>"
+ "<h1>Do U C Me?</h1>"
+ "Here is a long string that will wrap. "
+ "The effect we want is a multi-line label.";
JFrame f = new JFrame("Label Render Test");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
BufferedImage image = new BufferedImage(
400,
300,
BufferedImage.TYPE_INT_RGB);
Graphics2D imageGraphics = image.createGraphics();
GradientPaint gp = new GradientPaint(
20f,
20f,
Color.red,
380f,
280f,
Color.orange);
imageGraphics.setPaint(gp);
imageGraphics.fillRect(0, 0, 400, 300);
JLabel textLabel = new JLabel(title);
textLabel.setSize(textLabel.getPreferredSize());
Dimension d = textLabel.getPreferredSize();
BufferedImage bi = new BufferedImage(
d.width,
d.height,
BufferedImage.TYPE_INT_ARGB);
Graphics g = bi.createGraphics();
g.setColor(new Color(255, 255, 255, 128));
g.fillRoundRect(
0,
0,
bi.getWidth(f),
bi.getHeight(f),
15,
10);
g.setColor(Color.black);
textLabel.paint(g);
Graphics g2 = image.getGraphics();
g2.drawImage(bi, 20, 20, f);
ImageIcon ii = new ImageIcon(image);
JLabel imageLabel = new JLabel(ii);
f.getContentPane().add(imageLabel);
f.pack();
f.setLocationByPlatform(true);
f.setVisible(true);
}
});
}
}

Writing String into a image in java

I am trying to write a string into a image using ImageIo. But while writing a large string ,full string is not written into that image.
Here's my code:
File url=new File(imgUrl);
BufferedImage image = ImageIO.read(url);
Graphics g = image.getGraphics();
g.setPaintMode();
g.setFont(g.getFont().deriveFont(30f));
g.drawString(text, 100, 100);
g.dispose();
This code works fine for small strings.but when the width of the string exceeds the width of the image,then full string is not displayed on that image.
Any suggestions?
i have an old method try it
public BufferedImage stringToImage(String text, Font font, Color bgColor, Color fgColor) {
BufferedImage image = new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = (Graphics2D) image.getGraphics();
g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
FontRenderContext fc = g2d.getFontRenderContext();
Rectangle2D bounds = font.getStringBounds(text, fc);
//calculate the size of the text
int width = (int) bounds.getWidth();
int height = (int) bounds.getHeight();
image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
g2d = (Graphics2D) image.getGraphics();
g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setFont(font);
g2d.setColor(bgColor);
g2d.fillRect(0, 0, width, height);
g2d.setColor(fgColor);
g2d.drawString(text, 0, (int)-bounds.getY());
g2d.dispose();
return image;
}
and use
BufferedImage image = stringToImage(text, font, bgColor, fgColor);
ImageIO.write(image, "jpg", file);
Not tested, but it could be done as this:
JLabel label = new JLabel("<html><h2>Title</h2><p>large text ...</p>");
int w = image.getWidth();
int h = image.getHeigth();
label.setBounds(0, 0, w, h);
SwingUtilities.paintComponent(g, label, null, 0, 0, w, h);
There are many ways to acheive this.
FontRenderContext/GlyphVector as mentioned by pbaris. See this answer for an e.g.
FontMetrics as seen in this answer.
A JLabel (possibly multi-line) to contain and size the text. As mentioned by Joop E.G. LabelRenderTest
You can use JTextArea to layout text:
JTextArea textArea = new JTextArea(text);
textArea.setFont(g.getFont().deriveFont(30f));
textArea.setOpaque(false);
textArea.setWrapStyleWord(true);
textArea.setLineWrap(true);
textArea.setBounds(0, 0, image.getWidth(), image.getHeight());
textArea.paint(g);

Customize icon in Drag Drop Event?

I am dragging and dropping the jTable cell from one jTable to another jTable.For Now it is showing me default drag drop icon.
I am using TransferHandler class to implement this.
I Override getDragImage(image) to put my customize image But it is not working.
This way i implemented my code Implementation
I tried this code into this method.
File newFile = new File("./dragImage.jpeg");
Font font = new Font("Tahoma", Font.PLAIN, 11);
FontRenderContext frc = new FontRenderContext(null, true, true);
Rectangle2D bounds = font.getStringBounds(l_value, frc);
int w = (int) bounds.getWidth();
int h = (int) bounds.getHeight();
BufferedImage image = new BufferedImage(10,10, BufferedImage.TYPE_INT_RGB);
Graphics2D g = image.createGraphics();
g.setColor(Color.WHITE);
g.fillRect(0, 0, 10, 10);
g.setColor(Color.BLACK);
g.setFont(font);
g.drawString(l_value, (float) bounds.getX(), (float) -bounds.getY());
g.dispose();
return image;
This code is working in my main method but here in this function it is not working.

Categories

Resources