The three chief virtues of a programmer are: Laziness, Impatience and Hubris. Thus quoth Larry Wall, author of Perl, and his assertion applies equally well to other programming languages. Laziness, impatience and hubris certainly paid off for me on the first day of a recent programming stint.
My first assignment was to speed up an image management database application, specifically by improving the resizing of Jpegs. In my impatience to make a good first impression, I had the hubris to believe I could achieve the task on my first day. And, not giving laziness short shrift, I googled for existing code.
It didn't take me long to hit paydirt. In groups.google.com's searchable usenet archives, I found a component to resize jpeg files. I was particularly encouraged that the component was meant to be called from the command line, as that would be ideal from the context of the existing image management application.
Below is the code from the comp.lang.java.programmer usenet thread :
|
import java.awt.*; import java.awt.image.*; import java.io.*; import com.sun.image.codec.jpeg.*;
/** * Resizes jpeg image files on your file system. * Uses the com.sun.image.codec.jpeg package shipped * by Sun with Java 2 Standard Edition. * */ public class Resize extends Panel {
/** * @param originalImage the file name of the image to resize * @param newImage the new file name for the resized image * @param factor the new image's width will be width * factor. * The height will be proportionally scaled. */ public void doResize (String originalImage, String newImage, double factor) { Image img = getToolkit().getImage(originalImage); loadImage(img); int iw = img.getWidth(this); int ih = img.getHeight(this); //Reduce the image int w = (int)(iw * factor); Image i2 = img.getScaledInstance(w, -1, 0); loadImage(i2); //Load it into a BufferedImage int i2w = i2.getWidth(this); int i2h = i2.getHeight(this); BufferedImage bi = new BufferedImage(i2w, i2h, BufferedImage.TYPE_INT_RGB); Graphics2D big = bi.createGraphics(); big.drawImage(i2,0,0,this); //Use JPEGImageEncoder to write the BufferedImage to a file try{ OutputStream os = new FileOutputStream(newImage); JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(os); encoder.encode(bi); } catch(IOException ioe){ ioe.printStackTrace(); } } /** * Cause the image to be loaded into the Image object */ private void loadImage(Image img){ try { MediaTracker tracker = new MediaTracker(this); tracker.addImage(img, 0); tracker.waitForID(0); } catch (Exception e) {} }
public static void main(String args[]) { if(args.length != 3){usage();} double factor = Double.parseDouble(args[2]); Resize resizer = new Resize(); resizer.doResize(args[0], args[1], factor); System.exit(0); } public static void usage(){ System.out.println ("usage: java Resize original_file new_filename resize_factor"); System.exit(1); } } |