Reputation: 2784
There is a web site developed entirely in PHP with GD library that mainly deals with printing text over a random image.
The text has to be printed in any of about 100 prescribed TTF fonts (residing in a directory near the .php files) in a dozen of prescribed colors and there is a requirement to specify location of the text according to any of several prescribed algorithms.
This is solved by using imagettfbox() which returns geometry of the text, which is then mapped onto the image using imagettftext().
What can I use in Java to achieve the same functionality with servlets/beans? I can put the TTF fonts anywhere I have to. Registering them in Windows is undesirable, but if that's the only option we'd go for it (currently they are not).
@LexLythius:
From your link and some other resources I pieced together a working solution to drawing text over graphics:
// file is pointed at the image
BufferedImage loadedImage = ImageIO.read(file);
// file is pointed at the TTF font
Font font = Font.createFont(Font.TRUETYPE_FONT, file);
Font drawFont = font.deriveFont(20); // use actual size in real life
Graphics graphics = loadedImage.getGraphics();
FontMetrics metrics = graphics.getFontMetrics(drawFont);
Dimension size = new Dimension(metrics.getHeight(), metrics.stringWidth("Hello, world!"));
graphics.setFont(drawFont);
graphics.setColor(new Color(128, 128, 128); // use actual RGB values in real life
graphics.drawString("Hello, world!", 10,10); // use Dimension to calculate position in real life
What is remaining is displaying that image in a servlet and deciding what functionality goes where - to a servlet or bean.
Upvotes: 2
Views: 1906
Reputation: 11
You can get an OutputStream from the servlet response, and pass that OutputStream to ImageIO.write. Example based on the code from here (not my code): http://www.avajava.com/tutorials/lessons/how-do-i-return-an-image-from-a-servlet-using-imageio.html
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ImageServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.setContentType("image/jpeg"); // change this if you are returning PNG
File f = new File( /* path to your file */ );
BufferedImage bi = ImageIO.read(f);
// INSERT YOUR IMAGE MANIPULATION HERE
OutputStream out = response.getOutputStream();
ImageIO.write(bi, "jpg", out); // or "png" if you prefer
out.close(); // may not be necessary; containers should do this for you
}
Depending on how much memory you have, pre-loading the fonts and keeping a pool of them may save a bit of time.
Upvotes: 1