The Kahimyang Project Logo
Primo's Code Blog
Howtos tips and tricks
The Kahimyang Project

Download and crop an image direct from a servlet

This blog is a demonstration on how to download an image and crop them directly just before the servlet writes the image into the response. This is useful in instances where you don't want the downloaded image saved before they are consumed.

The following is that servlet, it takes two parameters, the url of the image, and the image type. Add parameters as your application may require. Please refer to the inline comments for more information.

package info.kahimyang.storm;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(name = "ImageDownloader", urlPatterns = {"/ImageDownloader"})
public class ImageDownloader extends HttpServlet {

    protected void processRequest(HttpServletRequest request, 
            HttpServletResponse response)
            throws ServletException, IOException {

        // Get values of parameters
        String imageType = request.getParameter("type");
        String media = request.getParameter("image_url");

        // Fetch the image
        URL url = new URL(media);
        HttpURLConnection connection = 
                (HttpURLConnection) url.openConnection();
        
        connection.addRequestProperty("User-Agent", "Mozilla");
        
        // Read the image into a BufferedImage object
        InputStream stream = connection.getInputStream();
        BufferedImage image = ImageIO.read(stream);

        // Get the dimension of the image
        int H = image.getHeight();
        int W = image.getWidth();

        // Crop the image from the top.  This example crops our
        // image 70 pixels from the top
        BufferedImage cropped = image.getSubimage(0, 70, W, H - 70);
        
        // Write the image into ByteArrayOutputStream
        ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
        ImageIO.write(cropped, imageType, byteStream);

        // Update response
        ServletOutputStream out = response.getOutputStream();
        response.setContentType("image/" + imageType);
        response.setContentLength(byteStream.size());

        out.write(byteStream.toByteArray());
        
        out.flush();
        out.close();

    }
 
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    @Override
    public String getServletInfo() {
        return "Short description";
    }
}

Note that this servlet uses WebServlet annotation in line 17 above to declare the servlet instead of updating the web.xml descriptor.

From your JSF or HTML page call the servlet similar to shown below:

<!-- storm below should be your application name -->
<img src="/storm/ImageDownloader?image_url=http://somewhere.com/image.gif&type=gif" />

That's it Good Luck.

RSS Logo



Related articles

Comment icon   Comments (Newest first)

Recent posts in Java/JSF category
Blue dot icon Using Rhinoslider with image and youtube content in JSF pages
Blue dot icon A dynamic standard sitemap.xml with Google image extension implemented as a Java Servlet
Blue dot icon Creating a Facebook-like panel with slim scrollbars and infinite scrolling in PrimeFaces
Blue dot icon Generating XML RSS 2 feeds with JDOM 2 with a servlet
Blue dot icon Building a page with infinite scroll in PrimeFaces using Waypoints jQuery plugin
Blue dot icon Implementing a collapsible ui:repeat rows in JSF
Blue dot icon Validating an email address in PrimeFaces p:inputText field with p:ajax





Most popular articles
Blue dot icon Using Expect script to automate SSH logins and do routine tasks accross multiple hosts   (15404)
Blue dot icon How to setup Tomcat 7 as your primary webserver on Debian Squeeze    (14083)
Blue dot icon How to setup FLV streaming with crtmpserver C++ RTMP server   (9863)
Blue dot icon A Java class for sending multipart Email messages through your Gmail account    (6980)
Blue dot icon How to use Google Translate's Text to Speech (TTS) services in your web page using Servlet   (5679)
Blue dot icon Speed up Primefaces page load with p:remoteCommand partial update   (5553)
Blue dot icon Building a mobile website with JSF 2 core and JQuery Mobile 1.0   (5333)
Blue dot icon Google Map-Adding markers, info window, circle, small control, and events in Javascript    (5240)