I'm currently working on projects that required generated watermark image on the fly using Java. I search on the Internet and try to find a third party Java API to help me accomplish my object. The result is little, some Java API like
GIF4J, even a light version, will cost me couple hundreds US bucks. I tried to search for Java tutorials, but there is almost none. Luckily, I got some hints from different Java forums and finally get it to work :). I want to shared it with you on here.
TutorialI assume you have basic knowledge of Java Servlet, JSP and HTML before you start.
Sample Picture:
Sample Watermark:
Result:
JSP Source:
While define the source "
src" of the image in your JSP, point it to your watermark servlet that you will create next.
<img name="myphoto" src="/servlet/WatermarkUtil" alt="mytest" style="background-color:#FFFFFF" />Remember to config your
web.xml for your servlet in JSP container.
Servlet Source:Create a Java servlet class, add the following code in your doGet & doPost methods.
import java.awt.*;
import java.awt.image.*;
import java.io.*;
import java.net.*;
import javax.imageio.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class WatermarkUtil extends HttpServlet
{
public void doGet(...) throws ...
{
doPost(...);
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ...
{
// load in the sample picture
URL url1 = new URL( "http://sample_picture.jpg" );
BufferedImage im = ImageIO.read(url1);
// load in the watermark image
URL url2 = new URL("http://watermark_image.gif");
BufferedImage im2 = ImageIO.read(url2);
// adjust the Alpha value of watermark image
Graphics2D g = im.createGraphics();
g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.6f));
// combine(overlay) both images, you can adjust the pos of watermark here.
g.drawImage(im2, (im.getWidth()-im2.getWidth())/2, (im.getHeight()-im2.getHeight())/2, null);
g.dispose();
// remember to define your content type of your response
response.setContentType("image/jpg");
// grab the servlet outputstream
ServletOutputStream out = response.getOutputStream();
// write your combined imaged to the response output stream
ImageIO.write( im, "jpeg", out );
//display and close output stream
out.flush();
out.close();
}
}
I hope you enjoy this tutorial.