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

Thursday, December 17, 2009

Java Sample Algorithms

Contains some sample algorithms That I wrote and thought of publishing. This post will be updated from time to time,depending on the rate I write them. Hope this will be useful to someone.The Language I've used here in writing these algorithms is Java.

1. Euclid's Algorithm to Find the GCD (Greatest Common Divisor)
      private int findGcd(int m, int n) {  
           do {  
                if (m > n) {  
                     m = m - n;  
                }  
                if (n > m) {  
                     n = n - m;  
                }  
                if (m == n) {  
                     m = m - n;  
                }  
           } while (m > 0);  
           return n;  
      }  

Tuesday, December 15, 2009

Java One Liners Collection

Today while I was going through my discrete maths notes It occurred to me that there are some algorithms that we could easily implement as just one liners. I just thought of publishing them so that they could be useful to anyone in the future. Please don't forget to comment and also add more algorithms of this style if you have. Also the last algorithm is left for you to be implemented :-).

The Following Class contains the Code 
  /**   
  *    
  * @author SHEN   
  */   
  public class OneLinerAlogrothmCollection {   
    /*   
     * One Liner Algorithm for Calculating the Corresponding Fibonachi series   
     * number for a given integer   
     */   
    public int fib(int n) {   
       {   
         return (n <= 2) ? 1 : fib(n - 1) + fib(n - 2);   
       }   
    }   
    /*   
     * One Liner Algorithm for Calculating the Corresponing Factorial for a   
     * Given Integer   
     */   
    public int fact(int n) {   
       return (n <= 1) ? 1 : fact(n - 1) * n;   
    }   
    /*   
     * One Liner Algorithm for Determining if a given Number is a Perfect Square   
     * or not   
     */   
    public boolean isPerfectSquare(int n) {   
       return (n > 1) ? (n & (n - 1)) == 0 : false;   
    }   
    /*   
     * One Liner Algorithm for Determining if a Given integer is a odd or a even   
     * integer returns : true -> for even integers false -> for odd integers   
     */   
    public boolean isEven(int n) {   
       return (n & 1) == 0;   
    }   
    /*   
     * One Liner Algorithm for Determining if a Given Integer is a Prime Number   
     * returns : true -> for prime integers false -> for others   
     */   
    public boolean isPrime(int input) {   
       throw new UnsupportedOperationException("It's Up to You to Implement this");   
    }   
  }