Converting images from gif to jpg for web or other reason can be done easily using the ImageIO package. The following snippet convert all the gif images in directory rootDir to jpg images.Compile this class and execute using java command line. This utility class is also available as part of the Livrona Tools Project.The following is the code for the Image Converter.
package com.livrona.image.tools;
import java.awt.image.BufferedImage; import java.io.File; import java.io.FilenameFilter; import java.util.Date;
import javax.imageio.ImageIO;
/** * @author mvohra * */ public class ImageConverter {
public static void main(String args[]) { // root directory where gif images are stored String rootDir = "c:\\gif-image-dir"; File dir = new File(rootDir);
// It is also possible to filter the list of returned files. // This example does not return any files that start with `.'. FilenameFilter filter = new FilenameFilter() { public boolean accept(File dir, String name) { return name.endsWith("gif"); } }; String[] children = dir.list(filter);
for (int i = 0; i < children.length; i++) { // Get filename of file or directory String filename = children[i]; log("Converting " + filename);
File myGifFile = new File(rootDir + "\\" + filename); File outFile = new File(rootDir + "\\" + filename.replace("gif", "jpg")); try { // Using Image IO BufferedImage bufi = ImageIO.read(myGifFile); ImageIO.write(bufi, "JPEG", outFile); } catch (Exception e) { log(e.getMessage()); } }
}
public static void log(String msg) { System.out.println(new Date() + " - " + msg); } }
|
Usage: java com.livrona.image.tools.ImageConverter c://web//images