|
Hey everyone,
There is a problem I have, and I was hoping someone might help me.
I develop using j2ee, and I am looking for a way to put a text on a jpeg picture so it can be saved as a new picture together with text (Like a watermark).
Thanks for any help, code examples would be welcomed.
Natasha
|
|
|
import java.awt.*;
import java.awt.event.*;
import java.awt.font.*;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.*;
import javax.imageio.ImageIO;
import javax.imageio.stream.ImageInputStream;
import javax.swing.*;
public class TextOnImage extends JPanel
{
BufferedImage image;
public TextOnImage(BufferedImage image)
{
this.image = image;
}
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
int w = getWidth();
int h = getHeight();
int x = (w - image.getWidth())/2;
int y = (h - image.getHeight())/2;
g.drawImage(image, x, y, this);
drawString(g, w, h);
}
private void drawString(Graphics g, int width, int height)
{
Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
Font font = g2.getFont().deriveFont(22f);
g2.setFont(font);
String s = "hello world";
FontRenderContext frc = g2.getFontRenderContext();
float w = (float)font.getStringBounds(s, frc).getWidth();
LineMetrics lm = font.getLineMetrics(s, frc);
float sx = (width - w)/2;
float sy = (height + lm.getHeight())/2 - lm.getDescent();
g2.setPaint(Color.red);
g2.drawString(s, sx, sy);
}
private void save()
{
int w = image.getWidth();
int h = image.getHeight();
BufferedImage bi = new BufferedImage(w, h, image.getType());
Graphics2D g2 = bi.createGraphics();
g2.drawImage(image, 0, 0, this);
drawString(g2, w, h);
g2.dispose();
String ext = "png"; // jpg, bmp (j2se 1.5)
try
{
ImageIO.write(bi, ext, new File("textOnImage." + ext));
}
catch(IOException ioe)
{
System.err.println("write error: " + ioe.getMessage());
}
}
public static void main(String[] args) throws IOException
{
File file = new File("/forum/images/cougar.jpg");
ImageInputStream iis = ImageIO.createImageInputStream(file);
TextOnImage test = new TextOnImage(ImageIO.read(iis));
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(new JScrollPane(test));
f.setSize(400,400);
f.setLocation(200,200);
f.setVisible(true);
test.save();
}
}
|
|
|
|
|
|
|
|
|
|
|
|