Posts Tagged ‘java’

Java Image Utility Class

27 April 2010

Here you can find a simple image utility class to do some simple image operations in Java. ImageUtil class can find image width, height, file size and it can convert images to other formats. Some other functionalities like resizing image are coming soon. This class uses standard Java classes like ImageIO or BufferedImage, so you can learn basic image operations by examining this class.

Methods

All the documentation is inside the class in JavaDoc format but simple class outline is like this:

findBufferedImage(File imageFile) gets the BufferedImage object using the file. Many image operations are done with BufferedImage class.
findBufferedImageForJpeg(File jpegFile) gets the BufferedImage object using the JPEG file.
findWidth(File imageFile) gets width of the image
findHeight(File imageFile) gets height of the image
findWidthAndHeight(File imageFile) gets width and height of image in array format
findFileSize(File imageFile) gets file size in bytes
convertTo(File input, File output, String format) convert image file to another format. possible formats are jpg, png, gif, bmp
convertToGif(File input, File output) convert image to gif.
convertToPng(File input, File output) convert image to png
convertToBmp(File input, File output) convert image to bmp
convertToJpg(File input, File output, float quality) convert image to jpg

Sample

You can find the code below inside the main method of the class.

try{

	String filePath="d:/_dev/temp/"; //!!!do not forget to change this and the filename!!!
	File f = new File(filePath+"test.png");
	System.out.println("test.png: "+ImageUtil.findWidth(f)+"x"+ImageUtil.findHeight(f));

	f=ImageUtil.convertTo(f, new File(filePath+"/test.gif"), ImageUtil.GIF);
	System.out.println("test.gif: "+ImageUtil.findWidth(f)+"x"+ImageUtil.findHeight(f));

	f=ImageUtil.convertTo(f, new File(filePath+"/test.bmp"), ImageUtil.BMP);
	System.out.println("test.bmp: "+ImageUtil.findWidth(f)+"x"+ImageUtil.findHeight(f));

	f=ImageUtil.convertToJpg(f, new File(filePath+"/test.jpg"), 0.9f);
	System.out.println("test.jpg: "+ImageUtil.findWidth(f)+"x"+ImageUtil.findHeight(f));

}
catch(Exception e){
	e.printStackTrace();
}

Download The Class

Download the class code from here.

ImageUtil Class Code

package net.gudubeth.common;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import javax.imageio.ImageIO;

import com.sun.image.codec.jpeg.ImageFormatException;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageDecoder;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import java.io.FileOutputStream;

/**
 * Image utility class. it can find image width, height, file size
 * and it can convert images to other formats. Images are used as File objects.
 * How to create a File object from file name:
 *  File file=new File("/path/to/image.jpg");
 *
 *
 * @author gudubeth
 * @since 20-01-2010
 */
public class ImageUtil{

    public static final String JPG="jpg";
    public static final String GIF="gif";
    public static final String BMP="bmp";
    public static final String PNG="png";

    /**
     * creates BufferedImage from file. this object is used for other image operations
     * @param imageFile
     * @return image
     * @throws ImageFormatException
     * @throws IOException
     */
    public static BufferedImage findBufferedImage(File imageFile) throws ImageFormatException, IOException{
            return ImageIO.read(imageFile);
    }

    /**
     * creates BufferedImage from jpg file. this object is used for other image operations
     * @param imageFile
     * @return image
     * @throws ImageFormatException
     * @throws IOException
     */
    public static BufferedImage findBufferedImageForJpeg(File imageFile) throws ImageFormatException, IOException{
            JPEGImageDecoder jpegDecoder = JPEGCodec.createJPEGDecoder(new FileInputStream(imageFile.getPath()));
            return jpegDecoder.decodeAsBufferedImage();
    }

    /**
     * gets the width of image.
     * @param imageFile these formats are ok: jpg,tif,png,bmp,gif. test for other formats
     * @return image width in int
     * @throws ImageFormatException
     * @throws IOException
     */
    public static int findWidth(File imageFile) throws ImageFormatException, IOException {
            return findBufferedImage(imageFile).getWidth();
    }

    /**
     * gets the height of image
     * @param imageFile. these formats are ok: jpg,tif,png,bmp,gif. test for other formats
     * @return image height in int
     * @throws ImageFormatException
     * @throws IOException
     */
    public static int findHeight(File imageFile) throws ImageFormatException, IOException{
            return findBufferedImage(imageFile).getHeight();
    }

    /**
     * find image width and height. this is faster than calling
     * findHeight and findWidth separately
     * @param imageFile
     * @return  int array containing width and height
     * @throws ImageFormatException
     * @throws IOException
     */
    public static int[] findWidthAndHeight(File imageFile) throws ImageFormatException, IOException{
            BufferedImage buffy = findBufferedImage(imageFile);
            return new int[]{buffy.getWidth(), buffy.getHeight()};
    }

    /**
     * find file size in bytes
     * @param imageFile
     * @return
     * @throws IOException
     */
    public static long findFileSize(File imageFile) throws IOException{
            return imageFile.length();
    }

    /**
     * convert image file to another format.  possible formats are jpg, png, gif, bmp
     *
     * @param input File        file to convert. any format read by ImageIO is OK
     * @param output File       output file
     * @param format String     one of jpg, png, gif, bmp
     * @return output file
     * @throws IOException
     */
    public static File convertTo(File input, File output, String format) throws IOException{
        ImageIO.write(ImageIO.read(input), format, output);
        return output;
    }

    /**
     * convert image to gif
     * @param input     file to convert
     * @param output    output file
     * @return output file
     * @throws IOException
     */
    public static File convertToGif(File input, File output) throws IOException{
        return convertTo(input, output, GIF);
    }

    /**
     * convert image to bmp
     * @param input     file to convert
     * @param output    output file
     * @return output file
     * @throws IOException
     */
    public static File convertToBmp(File input, File output) throws IOException{
        return convertTo(input, output, BMP);
    }

    /**
     * convert image to png
     * @param input     file to convert
     * @param output    output file
     * @return output file
     * @throws IOException
     */
    public static File convertToPng(File input, File output) throws IOException{
        return convertTo(input, output, PNG);
    }

    /**
     * convert image to jpg with specified quality
     * @param input     file to convert
     * @param output    output file
     * @param quality   jpeg quality. any float between 0 and 1.
     * @return output file
     * @throws ImageFormatException, IOException
     */
    public static File convertToJpg(File input, File output, float quality) throws ImageFormatException, IOException {
        if(quality>1 || quality<=0) throw new IllegalArgumentException("quality must be between 0 and 1"); 

        BufferedImage bim = findBufferedImage(input);
        FileOutputStream fos = new FileOutputStream(output);
        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(fos);
        JPEGEncodeParam encodeParams = encoder.getDefaultJPEGEncodeParam(bim);
        encodeParams.setQuality(quality, false);
        encoder.setJPEGEncodeParam(encodeParams);
        encoder.encode(bim);
        fos.close();
        return output;
    }

    /**
     *
     */
    public static void main(String[] args) {
        try{

            String filePath="d:/_dev/temp/"; //!!!do not forget to change this and the filename!!!
            File f = new File(filePath+"test.png");
            System.out.println("test.png: "+ImageUtil.findWidth(f)+"x"+ImageUtil.findHeight(f));

            f=ImageUtil.convertTo(f, new File(filePath+"/test.gif"), ImageUtil.GIF);
            System.out.println("test.gif: "+ImageUtil.findWidth(f)+"x"+ImageUtil.findHeight(f));

            f=ImageUtil.convertTo(f, new File(filePath+"/test.bmp"), ImageUtil.BMP);
            System.out.println("test.bmp: "+ImageUtil.findWidth(f)+"x"+ImageUtil.findHeight(f));

            f=ImageUtil.convertToJpg(f, new File(filePath+"/test.jpg"), 0.9f);
            System.out.println("test.jpg: "+ImageUtil.findWidth(f)+"x"+ImageUtil.findHeight(f));

        }
        catch(Exception e){
            e.printStackTrace();
        }
    }

}

Disabling browser caching

03 January 2010

There are two basic ways of disabling browsers to cache your web page. You can add related meta tags inside the head part of html or add response headers to page at the server side if you are using server side programming languages like PHP, Java/JSP or ASP.NET.

1. Disabling browser caching inside HTML

<meta http-equiv=”Pragma” content=”No-Cache” />
<meta http-equiv=”cache-control” content=”no-cache, no store” />
<meta name=”Expires” content=”Mon, 26 Jul 1997 05:00:00 GMT” />

Add the code above inside <head></head> tags of your page. The main disadvantage of this technique is that you can’t use inside non-html pages like XML or RSS.

2. Disabling the browser from caching at the server side

To prevent caching you have to add some headers to response. You can find code samples for PHP, ASP.NET and Java/JSP above. You can add these header to any kind of pages / files.

PHP

 header("Expires: Mon, 01 Jul 1990 05:00:00 GMT");
 header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
 header("Cache-Control: no-store, no-cache, must-revalidate");
 header("Cache-Control: post-check=0, pre-check=0", false);
 header("Pragma: no-cache");

ASP.NET

Response.ClearHeaders();
Response.AppendHeader("Cache-Control", "no-cache"); //HTTP 1.1
Response.AppendHeader("Cache-Control", "private"); // HTTP 1.1
Response.AppendHeader("Cache-Control", "no-store"); // HTTP 1.1
Response.AppendHeader("Cache-Control", "must-revalidate"); // HTTP 1.1
Response.AppendHeader("Cache-Control", "max-stale=0"); // HTTP 1.1
Response.AppendHeader("Cache-Control", "post-check=0"); // HTTP 1.1
Response.AppendHeader("Cache-Control", "pre-check=0"); // HTTP 1.1
Response.AppendHeader("Pragma", "no-cache"); // HTTP 1.0
Response.AppendHeader("Expires", "Mon, 26 Jul 1997 05:00:00 GMT"); // HTTP 1.0

I found this ASP.NET code at Stackoverflow: Making Sure a Web Page is not Cached Across All Browsers. I hope it works (:

Java

response.setHeader("Cache-Control","no-cache"); //HTTP 1.1
response.setHeader("Pragma","no-cache"); //HTTP 1.0
response.setDateHeader ("Expires", -1); //proxy level cache disabling
Categories: Coding
Tags: , , ,
continue >