Monday, July 20, 2009

JSP - JAVA Thumbnail Script

Creating thumbnail using JSP/JAVA

Generating thumbnail using Java Bean and JSP.

Code Snippet

STEP 1 : Create JavaBean named Thumbnail.java , Compile the class as package (MyPackage)
--------------------------------------------

package MyPackage
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.* ;
import java.awt.* ;
import java.util.Random;
import java.awt.Color;
import java.awt.image.*;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import java.awt.geom.AffineTransform;

/*
* Create Thumbnail image on the fly.
* Code may generate some performance issue
* For local or internal use, this can be powerful
* Can modify the scaling parameter for better thumbnail creation
*/

public class Thumbnail
{
private HttpServletResponse httpResponse; // If useful //
public String ioError;
public Thumbnail()
{
httpResponse = null;
ioError = "";
}
/*
* Generate GD Compatible of the Image Instance
* Java Graphics GD 2 will be the default Graphics Context
*/
public BufferedImage toCompatibleImage(BufferedImage image, GraphicsConfiguration gc)
{
if(gc==null){
gc = this.getDefaultConfiguration();
}
int w = image.getWidth();
int h = image.getHeight();
int transparency = image.getColorModel().getTransparency();
BufferedImage result = gc.createCompatibleImage(w, h, transparency);
Graphics2D g2 = result.createGraphics();
g2.drawRenderedImage(image, null);
g2.dispose();
return result;
}

/*
* Get teh default Graphics configuration
*/
public GraphicsConfiguration getDefaultConfiguration()
{
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice gd = ge.getDefaultScreenDevice();
return gd.getDefaultConfiguration();
}
/*
* Copy Image to New Graphics Context Image
*/
public BufferedImage copy(BufferedImage source, BufferedImage target)
{
Graphics2D g2 = target.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
double scalex = (double) target.getWidth()/ source.getWidth();
double scaley = (double) target.getHeight()/ source.getHeight();
AffineTransform xform = AffineTransform.getScaleInstance(scalex, scaley);
g2.drawRenderedImage(source, xform);
g2.dispose();
return target;
}

/*
* Resized Image and make the copy using the copy Func
*/
public BufferedImage getScaledInstance(BufferedImage image, int width, int height, GraphicsConfiguration gc)
{
if (gc == null){
gc = getDefaultConfiguration();
}
int transparency = image.getColorModel().getTransparency();
return copy(image, gc.createCompatibleImage(width, height, transparency));
}

/*
* Entry to the class
* Call to create the thumbnail
* Output will be the ServletOutputStream
*/
public void createThumb(HttpServletResponse response,String filePath,String canvasWidth,String canvasHeight)
{
try{
File file = new File(filePath);
BufferedImage image = javax.imageio.ImageIO.read(file);
GraphicsConfiguration gc = this.getDefaultConfiguration();

/*
* Core of Image resize
* Calculate the thumbnail Height and width
* If any iissue comes with resizing modify the following code
* Thumb height-width is calculated based on canvas params suppied
*/

double cWidth = Double.valueOf(canvasWidth);
double cHeight = Double.valueOf(canvasHeight);
double currentWidth = image.getWidth();
double currentHeight = image.getHeight();
double ratio = currentWidth/currentHeight;
double thumbHeight = cHeight;
double thumbWidth = cWidth;

if(cWidth>=currentWidth && cHeight>=currentHeight){
thumbHeight = currentHeight;
thumbWidth = currentWidth;
}else if(currentWidth >= cWidth && currentHeight >= cHeight){
thumbWidth = cWidth;
double cRatio = currentWidth/thumbWidth;
thumbHeight = currentHeight/cRatio;
}else if(currentHeight>cHeight){
thumbHeight = cHeight;
double cRatio = currentHeight/thumbHeight;
thumbWidth = currentWidth/cRatio;
}else if(currentWidth>cWidth){
thumbWidth = cWidth;
double cRatio = currentWidth/thumbWidth;
thumbHeight = currentHeight/cRatio;
}

BufferedImage resizeImage = this.getScaledInstance(image, (int)thumbWidth, (int)thumbHeight, gc);
ServletOutputStream out1 = response.getOutputStream();
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out1);
encoder.encode(resizeImage);
}catch(IOException ioCin){
ioError = ioCin.toString();
}

}




}

--------------------------------------------

STEP 2:
Create another JSP File to include the JavaBean (ie thumb.jsp )
------------------------------------------------------------------
//import package - page import="MyPackage.*"


//Global Declaration

String filePath = "";
String width = "10";
String height = "10";
String type = "album";

//end global
//scriptlet
try{
filePath = request.getParameter("image");
width = request.getParameter("w");
height = request.getParameter("h");
type = request.getParameter("type");
}catch(Exception cin){
//out.print("EXP");
}

String uploadFolder = "";
if(type.equals("album")){
uploadFolder = "/uploads/album/";
}
String dest = config.getServletContext().getRealPath(uploadFolder+filePath);

// PARAMS : FILE PATH
// CANVAS WIDTH //
// CANVAS HEIGHT//
//out.print(dest);
Thumbnail tmb = new Thumbnail();
tmb.createThumb(response,dest,width,height);
//out.print(tmb.ioError);
//scriptlet


Step 3 : Using the Thumbnail Script in HTML OR JSP File
---------------------------------------------------------------

To resize an image using the script , use IMG SRC as follows,

 img src="http://www.blogger.com/thumb.jsp?image=/myimages/demo.jpg&w=160&h=100"  


// image -> path to image file
//w - canvas width
//h - canvas height



Note :

The method is not well suited for high resolution images . Load on the server may increase using the script . Normally, after uploading the image, resize and store the thumbnail in another folder. This may reduce load on the server.

0 comments: