Wednesday, December 23, 2009

Java Based Photo Organizer

Today,while going through my office x-mas party photos on fb, I came across a new idea that could be implemented quickly & could be very useful. It was a simple java class file that we can use to re-order the photos depending on their last modified time stamp. After about 3 hours of coding & testing I was able to produce the following piece of code.You can re-use this code to order them,number them and re-encode them. This is currently implemented in command line mode. But could be easily integrated to a java desktop of web application front end. I thought of publishing it as I thought it could be useful to anyone in the future.

Following is the Code Listing for the Java Based Photo Organizer Class
 import java.awt.image.BufferedImage;   
  import java.io.File;   
  import java.io.FilenameFilter;   
  import java.util.Arrays;   
  import java.util.Date;   
  import java.util.Iterator;   
  import java.util.List;   
  import java.util.Scanner;   
  import javax.imageio.ImageIO;   
  /**   
  *    
  * @author mootarpe   
  */   
  public class PhotoSorterMain {   
    // Program Constants   
    private static String IMAGE_PREFIX = "shen747";   
    private static int IMAGE_ST_INDEX = 1;   
    private static final String OUT_FOLDER = "sorted_out";   
    /* Method Sorting the Images Using Binary Sort Algorithm */   
    private List sortImages(List imageList) throws Exception {   
       // Convert List to Array   
       File[] f = (File[]) imageList.toArray(new File[0]);   
       // Sort the Array Uisng bubble sort   
       for (int i = 0; i < (f.length - 1); i++) {   
         // Loop once for each element in the array.   
         for (int index = 0; index < (f.length - 1) - i; index++) {   
            // Once for each element, minus the counter.   
            if (getTimeStamp(f[index]) > getTimeStamp(f[index + 1])) {   
              // Test if need a swap or not.   
              System.out.println("Swapping File -> " + f[index].getName()   + " with " + f[index + 1].getName());   
              // These three lines just swap the two elements:   
              File temp = f[index];   
              f[index] = f[index + 1];   
              f[index + 1] = temp;   
            }   
         }   
       }   
       // Convert Again to List &amp; Return   
       return Arrays.asList(f);   
    }   
    /* Method Returning the Corresponding TimeStamp for an Image */   
    private Long getTimeStamp(File file) throws Exception {   
       return file.lastModified();   
    }   
    /* Method Listing the Photo List In the Directory */   
    private List getPhotoListInDirectory(String dirPath) throws Exception {   
       File dir = new File(dirPath);   
       File[] files = dir.listFiles(new FilenameFilter() {   
         public boolean accept(File dir, String name) {   
            if (name.endsWith(".jpg") | name.endsWith(".JPG")) {   
              return true;   
            } else {   
              return false;   
            }   
         }   
       });   
       // Converting the Array To List &amp; Returning   
       return Arrays.asList(files);   
    }   
    /* Method Writing the Photos to the Output Folder */   
    private void prepareImages(List photoList, String dir) throws Exception {   
       System.out.println("Received : " + photoList);   
       String seperator = System.getProperty("file.separator");   
       // Create Output Folder   
       File foutDir = new File(dir + seperator + OUT_FOLDER);   
       foutDir.mkdir();   
       // Write Files to the Output Folder   
       for (Iterator itr = photoList.iterator(); itr.hasNext();) {   
         File f = (File)itr.next();   
         System.out.println("\n\nEncoding File --&gt; " + f.getName());   
         // Writing the File Object Directly to File   
         String fileName = foutDir.getAbsolutePath() + seperator+ IMAGE_PREFIX + "-" + IMAGE_ST_INDEX + ".jpg";   
         System.out.println("New File Name --&gt;" + fileName+ " With time Stamp = "+ new Date(getTimeStamp(f)).toString());   
         // Copy the Files   
         BufferedImage bufImg1 = readImageFromFile(f);   
         writeImageToJPG(new File(fileName), bufImg1);   
         // Increating the Image Name Index   
         IMAGE_ST_INDEX++;   
       }   
    }   
    /*   
     * The Core Process Method Carring Out the Process (Bussiness Logic Method)   
     */   
    public boolean doPhotoSortingProcess(String photoDir) {   
       try {   
         // 1.Set the Photo Directory Path   
         String dir = photoDir;   
         // 2.Get the Photo List In The Directory   
         List photos = getPhotoListInDirectory(dir);   
         System.out.println("PHOTOS : " + photos);   
         // 3.Sort The Photo List &amp; Derefecne the List Obj   
         List sortedImages = sortImages(photos);   
         // 4.Out put the sorted List to a output folder   
         prepareImages(sortedImages, dir);   
         // 5.Clean Up Everything/Return Status   
         return true;   
       } catch (Exception ex) {   
         System.out.println("The following Exception Occured : "+ ex.getMessage());   
         ex.printStackTrace();   
         return false;   
       }   
    }   
    /* Method Reading a Image to a buffer */   
    public static BufferedImage readImageFromFile(File file) throws Exception {   
       return ImageIO.read(file);   
    }   
    /* Method Writing a File as a JPEG Image */   
    public static void writeImageToJPG(File file, BufferedImage bufferedImage)   
         throws Exception {   
       ImageIO.write(bufferedImage, "jpg", file);   
    }   
    // Main Method For Local Testing   
    public static void main(String[] args) {   
       // Modified to Command Line Mode   
       Scanner s = new Scanner(System.in);   
       // Getting Input   
       System.out.println("Enter Picture Directory Path and Press Enter : ");   
       String dir = s.nextLine();   
       System.out.println("You Entered : " + dir);   
       PhotoSorterMain phm = new PhotoSorterMain();   
       boolean status = phm.doPhotoSortingProcess(dir);   
       System.out.println("Photo Ordering Status : " + status);   
    }   
  }   

No comments: