Thursday, September 11, 2008

Watermarking Images in a Java Servlet

Delicious 0
This is a helpful tuotiral about adding watermark into images. Someone wants to upload image to server and watermarks image, read it, it'll resolve your problem. It's not my tutorial, i dont write it, i found it in http://tutorial.jcwcn.com/Web-Design/Java/JSP-and-Servlets/2007-08-03/2591.html, but if you had any question about it, you can ask me, pleased to help you.

Setting up the Servlet
In the web.xml, you will need to configure a filter that will be used to call the servlet. By creating a filter, this will simplify the url used to access the servlet and image. To an end user, the filter will look like part of the directory structure for the image.

The servlet will be invoked when the url contains the pattern /watermark/*. In our example, we will place the images in a directory called photos in the web application directory. To view the image without the watermark, you would use the url http://webserver/webapp/photos/car.jpg. To invoke the servlet, you would use the url http://webserver/webapp/watermark/photos/car.jpg.

<servlet>
  <servlet-name>com.codebeach.servlet.WatermarkServlet</servlet-name>
  <servlet-class>com.codebeach.servlet.WatermarkServlet</servlet-class>
  </servlet>
<servlet-mapping>
  <servlet-name>com.codebeach.servlet.WatermarkServlet</servlet-name>
  <url-pattern>/watermark/*</url-pattern>
  </servlet-mapping>

Getting the File Name
When the servlet is invoked, the first thing we need to do is to know which file is being requested to have a watermark added.

File file = new File(req.getPathTranslated());
if (!file.exists())
{
     res.sendError(res.SC_NOT_FOUND);
     return;
}
The getPathTranslated() method of the HttpServletRequest object provides the file name with the that was specified on the url after the watermark filter. If the requested file does not exist, this will return a not found error.

Loading and Drawing the Image
Next,we will load the image and draw it onto a BufferedImage. It is being drawn on to a BufferedImage to allow us to modify the image by adding a watermark to it before it is sent to the web browser.
ImageIcon photo = new ImageIcon(req.getPathTranslated());


//Create an image 200 x 200
BufferedImage bufferedImage = new BufferedImage(photo.getIconWidth(),
                                                photo.getIconHeight(),
                                                BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = (Graphics2D) bufferedImage.getGraphics();
g2d.drawImage(photo.getImage(), 0, 0, null);
Creating the AlphaComposite
To allow us to see through the watermark, we will create an AlphaComposite. For our example, we will use a value of 50%. Since we are only drawing text in our tutorial for the watermark, we could have easily created a Color object where the alpha level was 50%. AlphaComposite allows more flexibility since it can be used when you draw anything on top of the the source image. So if you want to use your logo as a watermark, the code for blending it with the source image will be the same.
//Create an alpha composite of 50%
AlphaComposite alpha = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f);
g2d.setComposite(alpha); 
Drawing the Watermark
Since we have set the AlphaComposite, we now need to draw the text on the source image. For this example, we will set the color to white, enable text anti-aliasing, and a font of Arial Bold 30 point. There are a number of ways you could draw the watermark on the image. For this example, we will simply center the text by determining the sizes of the image and rectangle of the rendered string.
g2d.setColor(Color.white);
g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
                     RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

g2d.setFont(new Font("Arial", Font.BOLD, 30));

String watermark = "Copyright ?2006";

FontMetrics fontMetrics = g2d.getFontMetrics();
Rectangle2D rect = fontMetrics.getStringBounds(watermark, g2d);

g2d.drawString(watermark, (photo.getIconWidth() - (int) rect.getWidth()) / 2,
                          (photo.getIconHeight() - (int) rect.getHeight()) / 2);

//Free graphic resources
g2d.dispose();
Creating a JPG
The final step is to write the image to the response output stream as a jpg. To do this, we will use the ImageIO class that was introduced with Java 1.4. The ImageIO class allows you to write an Image object to JPG, PNG, BMP, and WBMP. In Java 1.6, you will be able to write an Image as GIF.

//Set the mime type of the image
res.setContentType("image/jpg");

//Write the image as a jpg
OutputStream out = res.getOutputStream();
ImageIO.write(bufferedImage, "jpg", out);
out.close();
The ImageIO class will write the bufferedImage as a jpg to the output stream from the HttpServletResponse object.
The Results
To access the image, you can place the servlet call in an <img> tag or directly from the URL.
Original Image

 
Watermarked Image

Wrapping It Up
Below is the complete example of creating a watermark on an image from a servlet


package com.codebeach.servlet;

    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.awt.*;
    import java.awt.image.*;
    import javax.imageio.*;
    import javax.swing.ImageIcon;
    import java.awt.geom.Rectangle2D;

    public class WatermarkServlet extends HttpServlet
    {
        public void doGet(HttpServletRequest req, HttpServletResponse res)
        {

            try
            {
                File file = new File(req.getPathTranslated());
                if (!file.exists())
                {
                    res.sendError(res.SC_NOT_FOUND);
                    return;
                }

                ImageIcon photo = new ImageIcon(req.getPathTranslated());

                //Create an image 200 x 200
                BufferedImage bufferedImage = new BufferedImage(photo.getIconWidth(),
                        photo.getIconHeight(),
                        BufferedImage.TYPE_INT_RGB);
                Graphics2D g2d = (Graphics2D) bufferedImage.getGraphics();

                g2d.drawImage(photo.getImage(), 0, 0, null);

                //Create an alpha composite of 50%
                AlphaComposite alpha = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 
      0.5f);
                g2d.setComposite(alpha);

                g2d.setColor(Color.white);
                g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
                                     RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

                g2d.setFont(new Font("Arial", Font.BOLD, 30));

                String watermark = "Copyright ?2006";

                FontMetrics fontMetrics = g2d.getFontMetrics();
                Rectangle2D rect = fontMetrics.getStringBounds(watermark, g2d);

                g2d.drawString(watermark,
                                (photo.getIconWidth() - (int) rect.getWidth()) / 2,
                                (photo.getIconHeight() - (int) rect.getHeight()) / 2);

                //Free graphic resources
                g2d.dispose();

                //Set the mime type of the image
                res.setContentType("image/jpg");

                //Write the image as a jpg
                OutputStream out = res.getOutputStream();
                ImageIO.write(bufferedImage, "jpg", out);
                out.close();
            }
            catch (IOException ioe)
            {
            }
        }
    }

Related Posts:

Dont just read, download and go, a thank will be helpful for the author to keep going a good job.

Share this post to tell other people about its

blog comments powered by Disqus