KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > snow > utils > PicRenamer


1 package snow.utils;
2
3 import java.io.*;
4 import java.nio.*;
5 import java.util.*;
6 import javax.imageio.*;
7 import java.awt.image.*;
8
9
10 /** convert/rewrite all images to PNG and jpeg in a directory and subdirectories
11
12     PNG => PNG
13     the rest => JPEG
14
15     Goal: progressive jpegs cause JVM crash when embedded in jar files !!
16
17 */

18 public final class PicRenamer
19 {
20
21   public PicRenamer(File base)
22   {
23     Vector<File> im = new Vector<File>();
24     getImagesRecurse(im, base);
25
26     System.out.println(""+im.size()+" images found in "+base.getAbsolutePath());
27
28     String JavaDoc[] wfn = ImageIO.getWriterFormatNames();
29     System.out.println("Supported Write Format");
30     for(int i=0; i<wfn.length; i++)
31     {
32       System.out.println(" "+wfn[i]);
33     }
34     System.out.println(".\n");
35
36     for(int i=0; i<im.size(); i++)
37     {
38       try{
39        convertFiles( im.elementAt(i));
40       } catch(Exception JavaDoc e) {e.printStackTrace();}
41     }
42
43
44
45   } // Constructor
46

47
48   /** convert GIF in PNG and rewrite jpegs
49   */

50   public void convertFiles(File in) throws Exception JavaDoc
51   {
52     BufferedImage im = ImageIO.read(in);
53     String JavaDoc outName = in.getAbsolutePath();
54     int posPt = outName.lastIndexOf(".");
55     String JavaDoc originalExtension = outName.substring(posPt+1).toUpperCase();
56
57     // delete the original
58
in.delete();
59
60     if(originalExtension.equals("PNG") || originalExtension.equals("GIF"))
61     {
62       outName = outName.substring(0,posPt) + ".PNG";
63       //System.out.println("writing "+outName);
64
ImageIO.write(im, "PNG", new File(outName));
65     }
66     else
67     {
68       outName = outName.substring(0,posPt) + ".JPEG";
69       System.out.println("writing "+outName);
70       ImageIO.write(im, "JPEG", new File(outName));
71     }
72   }
73
74
75
76   public void getImagesRecurse(Vector<File> im, File base)
77   {
78     for(File fi : base.listFiles())
79     {
80        if(fi.isDirectory())
81        {
82          getImagesRecurse(im, fi);
83        }
84        else
85        {
86          String JavaDoc name = fi.getName().toUpperCase();
87          if(name.endsWith(".JPG")) im.add(fi);
88          if(name.endsWith(".BMP")) im.add(fi);
89          if(name.endsWith(".PNG")) im.add(fi);
90          if(name.endsWith(".GIF")) im.add(fi);
91        }
92     }
93   }
94
95  /**
96   * Static main method
97   */

98   public static void main( String JavaDoc[] arguments )
99   {
100      new PicRenamer(new File("c:/sources/other/mail/client"));
101   } // main
102

103
104
105 } // PicRenamer
Popular Tags