Coding Category

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();
        }
    }

}

Email verification with PHP

19 January 2010

There are so many email verification functions written with PHP. But how many of them work perfect? In the search of perfect email verification with regular expression, the site fightingforalostcause.net has tested 13 of them and published the results at this page: Comparing E-mail Address Validating Regular Expressions. He found that Geert De Deckere from the Kohana project has the best one. Details are at the page above and here is the email verification function made of this regex.

/**
 *
 * @param  $email
 * @return bool true if email is valid
 */
function validateEmail($email){
	return (bool) preg_match('/^[-_a-z0-9\'+*$^&%=~!?{}]++(?:\.[-_a-z0-9\'+*$^&%=~!?{}]+)*+@(?:(?![-.])[-a-z0-9.]+(?<![-.])\.[a-z]{2,6}|\d{1,3}(?:\.\d{1,3}){3})(?::\d++)?$/iD', $email);
}

To calculate the difference between dates, PHP has a date_diff function but it only works in PHP version 5.3 and above. So we still need a date substraction function. Here you can find a simple one coded by me. You can find a detailed documentation in PHPDoc format below in the code section.

Usage

The function takes three parameters. Only the first one is mandatory.
dateDiff($d1[, $d2=null [, $format="all"]);

First two parameters are dates in unix timestamp format or any string strtotime functions accepts. This means you can use time() function to take the time or you possibly can use MySQL data directly with this function. Click to find about strtotime function. It doesn’t matter which date is bigger. Always positive result is returned. The last parameter tells the function in what format the result should be returned. You can choose one of “second”, “minute”, “hour”, “day”, “week”, “month” or “year” as a format. If you use one of these, the function returns the result as an integer. If you don’t use this parameter or set it as “all”, an array containing all the format parameters above will be returned. You can try it with this code: print_r(dateDiff(time(), “2009-12-04″));

Examples

echo "now:".date("r",time())."";
echo "1: ".dateDiff("20090401040302", time(), "month")." months";
echo "2: ".dateDiff(time(), "2009-07-23 04:00:00", "hour")." hours";
echo "3: ".dateDiff("-3 day", "2009-07-23 04:00:00", "day")." days";
echo "4: ".dateDiff("2008-06-23", "2009-07-23", "years")." years";

Code

/**
 * finds the difference between dates.
 * usage: dateDiff($d1[, $d2=null [, $format="all"]);
 * examples:
 *     dateDiff("20090401040302");
 *     dateDiff("20090401040302", time(), "month");
 *     dateDiff(time(), "2009-07-23 04:00:00", "hour");
 *     dateDiff("-3 day", "2009-07-23 04:00:00");
 *     dateDiff("2008-06-23", "2009-07-23", "years");
 *
 * @param mixed $d1     first date. can be unix timestamp or any date string
 *                      strtotime accepts.
 * @param mixed $d2     second date. if it is empty or not given,
 *                      the function uses the current time. which date is bigger or
 *                      smaller doesn't matters. can be an unix timestamp or any
 *                      date string strtotime accepts.
 * @param str $format   one of "second", "minute", "hour", "day", "week",
 *                      "month", "year", "all".
 *                      if it is empty or set as "all", all the types are
 *                      calculated and an array is returned. if not, result
 *                      is returned in specified format as an integer.
 * @return mixed        difference between dates as int or array depending on
 *                      the value of $format. if result is array, it contains
 *                      these parameters: "second", "minute", "hour", "day",
 *                      "week", "month", "year"
 */
function dateDiff($d1, $d2=null, $format="all"){
    if($d2==null){
        $d2=$d1;
        $d1=time();
    }

    if(!is_int($d1)) $d1=strtotime($d1);
    if(!is_int($d2)) $d2=strtotime($d2);
    $d=abs($d1-$d2);

    $format=strtolower($format);
    if(empty($format) || $format=="*") $format="all";
    if(strrpos($format, 's')==strlen($format)-1){
        $format=substr($format, 0, strlen($format)-1);
    }

    $result = array();

    if($format=="all" || $format=="day")    $result["day"]   = floor($d/(60*60*24));
    if($format=="all" || $format=="month")  $result["month"] = floor($d/(60*60*24*30));
    if($format=="all" || $format=="year")   $result["year"]  = floor($d/(60*60*24*365));
    if($format=="all" || $format=="week")   $result["week"]  = floor($d/(60*60*24*7));
    if($format=="all" || $format=="hour")   $result["hour"]  = floor($d/(60*60));
    if($format=="all" || $format=="minute") $result["minute"]= floor($d/60);

    if($format!="all") return $result[$format];
    else return $result;
}

The function below deletes directories with many options. You can delete directories recursively, delete only content of directories or remove files in a directory with regular expression. I wrote details in PHPDoc format.

/**
 * removes files in a directory
 * examples:
 * <pre>
 * removeDir('/home/gudubeth/pics');
 *      //delete everything and the directory itself.
 * removeDir('/home/gudubeth/pics', false);
 *      //delete only content of the directory. subdirectories are deleted too.
 * removeDir('/home/gudubeth/pics', false, false);
 *      //delete only content of the directory. subdirectories
 *      //are NOT deleted
 * removeDir('/home/gudubeth/pics', false, true, '/.*\.jpg/');
 *      //delete only jpg files inside this directory and its sub directories.
 * </pre>
 * @param str $dir  directory path
 * @param bool $deleteDir   deletes the directory itself if it is true.
 *                          default is true
 * @param bool $recursive   deletes files recursively if it is true.
 *                          default is true
 * @param str $regEx        deletes files only if they match this $regEx.
 *                          Regular expression checking is done with preg_match.
 *                          default is '/.*/' which means 'everything'
 * @return  bool    true if every file is deleted successfully or there are
 *                  no files found to delete. false if any of the deletions
 *                  is unsuccessful
 *
 * */
function removeDir($dir, $deleteDir=true, $recursive=true, $regEx="/.*/") {
    if(!$dh = @opendir($dir)) return false;
    $result=true;
    while (($file=readdir($dh))!==false) {
        if($file!='.' && $file!='..'){
            if(is_dir( $dir.'/'.$file) && $recursive)
                $result = removeDir($dir.'/'.$file, true, true, $regEx) && $result;
            else if(preg_match($regEx, $file))
                $result = @unlink($dir.'/'.$file) && $result;
        }
    }
    closedir($dh);
    if($deleteDir) $result = @rmdir($dir) && $result;
    return $result;
}
Categories: Coding
Tags: ,
continue >

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 >

Mini Ajax Library

26 December 2009

You need basic ajax functions and you need a simple, small library not like those big, complex libraries like prototype. Well, open source community hears you. MiniAjax is a lightweight ajax library which is only 1.4 kb without compression. MiniAjax can do simple form serializing, send request to a url, get its response by both GET or POST methods and insert the result in a html element if needed, submit a form.

Here is the Google Code page of this library: http://code.google.com/p/miniajax/ (Everything in one page). You can find discussions and some extra functions at DZone Snippets

If you need to convert accented characters to plain ones such as ğ to g, ä to a, ß to ss, here is the good news. Wordpress has already done this and you can freely use their implementation. I shortened the function a bit (remove the ‘remove accents for latin-1 charset’ part). You can find the original version in wp-inlcludes/formatting.php under the name of remove_accents or you can check formatting.php online at this site.

Usage:

echo remove_accents("ĞÜŞİÖÇÄËÏÃ ğüşıöçäëïã ");
//output: 'GUSIOCAEIA gusiocaeia'

(more…)

Categories: Coding
Tags: ,
continue >

Here is the crossbrowser javascript code for changing flash object’s size. Works fine in IE5.5, IE6, IE7, IE8, Firefox 3, Opera 10, Safari 4, Chrome 3.

Usage
Resizing Flash:
flashResizer.resize(width, height, flash_object_id);

Zoom In:
flashResizer.zoomin(flash_object_id);

Zoom Out:
flashResizer.zoomout(flash_object_id);

Javascript Code:

var flashResizer = {
    ZOOM_IN:1,ZOOM_OUT:-1,
    fo:null,ZOOM_FACTOR:0.1,
    findObj:function(_foid){if(_foid==undefined || _foid==null){return this.fo;}
        this.fo=null;if (window.document[_foid]) this.fo=window.document[_foid];
        else if (navigator.appName.indexOf("Microsoft Internet")==-1){
            if (document.embeds && document.embeds[_foid]) this.fo = document.embeds[_foid];}
        else this.fo = document.getElementById(_foid);return this.fo;},
    resize:function(_w,_h,_foid){if(this.findObj(_foid)){
            this.fo.width=_w;this.fo.height=_h;}return this;},
    zoom:function(_d,_f){if(this.findObj(_f)){var zf=1+_d*this.ZOOM_FACTOR;
            this.resize(this.fo.width*zf,this.fo.height*zf);}return this;},
    zoomin:function(_f){this.zoom(this.ZOOM_IN,_f);},
    zoomout:function(_f){this.zoom(this.ZOOM_OUT, _f);}
}

Same Javascript Code With Comments (Longer Code):

var flashResizer = {
    fo:null, //flash object
    ZOOM_FACTOR:0.1, // how much resizing will happen. used in zoom

    ZOOM_IN:1,
    ZOOM_OUT:-1,

    /**
     * find flash object - cross browser
     * look at http://blog.codefidelity.com/?p=14
     * @param _foid  DOM id of flash object. if no _foid is given,
     *               uses previously found flash object
     * @return       flash object. null if no object is found
     */
    findObj:function(_foid){
        if(_foid==undefined || _foid==null){
           return this.fo;
        }
        this.fo=null;
        if (window.document[_foid]) this.fo=window.document[_foid];
        else if (navigator.appName.indexOf("Microsoft Internet")==-1){
            if (document.embeds && document.embeds[_foid]) this.fo = document.embeds[_foid];
        }
        else this.fo = document.getElementById(_foid);

        return this.fo;
    },

    /**
     * resize flash to specified size
     * @param _w: new width
     * @param _h: new height
     * @param _foid: flash object id. if no _foid is given,
     *               uses previously found flash object.
     * @return this object
     */
    resize:function(_w, _h, _foid){
        if(this.findObj(_foid)){
            this.fo.width = _w;
            this.fo.height = _h;
        }
        return this;
    },

    /**
    * @param _d: zoom direction. flashResize.ZOOM_IN or 1 to zoom in,
    *            flashResize.ZOOM_OUT or-1 to zoom out.
    *            factor size also changes the zoom factor
    * @param _foid: flash object id. if no _foid is given,
    *               uses previously found flash object.
    * @return  this object
    */
    zoom:function(_d, _foid){
        if(this.findObj(_foid)){
            var zf = 1 + _d * this.ZOOM_FACTOR;
            this.resize(this.fo.width*zf, this.fo.height*zf);
        }
        return this;
    },

    /**
     * @param _foid: flash id. if no _foid is given, uses previously found flash object.
     */
    zoomin:function(_foid){
        return this.zoom(this.ZOOM_IN, _foid);
    },

    /**
     * @param _foid: flash id. if no _foid is given, uses previously found flash object.
     */
    zoomout:function(_foid){
        return this.zoom(this.ZOOM_OUT, _foid);
    }
}
Categories: Coding
Tags: ,
continue >

Some sites like Youtube use a simple  formatting style in comments’ date & times. Instead of writing long and detailed dates (like October 12, 2009 07:23 PM) , they use relative dates like 3 days ago, 2 weeks ago, etc.

The code below does the same thing. It takes your date,in any format php’s strtotime uses (which means, in most situations dates coming from your database can be used directly), and converts it into this simle format.

Click here for turkish version


/**
 * finds passed time in a readable format like
 * "2 days ago", "5 years ago", etc...
 * Sample usage:
 *  echo relativeTime("2009-08-23 12:05:14");
 * @param str $dateStr  date to calculate. any format readable by
 *                      php's strtotime function is appropriate.
 *                      check out http://www.php.net/manual/tr/function.strtotime.php
 *                      for usage of strtotime.
 * @param str $now      default is null which means running time. this is the
 *                      bigger date which $dateStr is substracted from.
 * @return str
 */
function relativeTime($dateStr, $now=null){
    if(!$now) $now=time();
    $time=$now-strtotime($dateStr);

    if($time<0) return "";

    if($time<60){$no=$time; $str="second";}
    else if($time<3600){$no=$time/60; $str="minute";}
    else if($time<86400){$no=$time/(3600); $str="hour";}
    else if($time<86400*7){$no=$time/(86400); $str="day";}
    else if($time<86400*30){$no=$time/(86400*7); $str="week";}
    else if($time<86400*365){$no=$time/(86400*30); $str="month";}
    else {$no=$time/(86400*365); $str="year";}

    return round($no)." ".$str.((round($no)>1)?"s":"")." ago";
}