private void createThumbnail(String filename, int thumbWidth, int thumbHeight, int quality, String outFilename)  
        throws InterruptedException, FileNotFoundException, IOException  
    {  
        // load p_w_picpath from filename  
        Image p_w_picpath = Toolkit.getDefaultToolkit().getImage(filename);  
        MediaTracker mediaTracker = new MediaTracker(new Container());  
        mediaTracker.addImage(p_w_picpath, 0);  
        mediaTracker.waitForID(0);  
        // use this to test for errors at this point: System.out.println(mediaTracker.isErrorAny());  
     
        // determine thumbnail size from WIDTH and HEIGHT  
        double thumbRatio = (double)thumbWidth / (double)thumbHeight;  
        int p_w_picpathWidth = p_w_picpath.getWidth(null);  
        int p_w_picpathHeight = p_w_picpath.getHeight(null);  
        double p_w_picpathRatio = (double)p_w_picpathWidth / (double)p_w_picpathHeight;  
        if (thumbRatio < p_w_picpathRatio) {  
            thumbHeight = (int)(thumbWidth / p_w_picpathRatio);  
        } else {  
            thumbWidth = (int)(thumbHeight * p_w_picpathRatio);  
        }  
     
        // draw original p_w_picpath to thumbnail p_w_picpath object and  
        // scale it to the new size on-the-fly  
        BufferedImage thumbImage = new BufferedImage(thumbWidth, thumbHeight, BufferedImage.TYPE_INT_RGB);  
        Graphics2D graphics2D = thumbImage.createGraphics();  
        graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);  
        graphics2D.drawImage(p_w_picpath, 0, 0, thumbWidth, thumbHeight, null);  
     
        // save thumbnail p_w_picpath to outFilename  
        BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(outFilename));  
        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);  
        JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(thumbImage);  
        quality = Math.max(0, Math.min(quality, 100));  
        param.setQuality((float)quality / 100.0f, false);  
        encoder.setJPEGEncodeParam(param);  
        encoder.encode(thumbImage);  
        out.close();  
    }