--- ImageUtil.java 2006-01-12 23:29:00.000000000 -0800 +++ D:\ImageUtil.java 2006-01-24 21:49:53.468750000 -0800 @@ -39,6 +39,7 @@ package com.sun.opengl.util; +import java.awt.*; import java.awt.image.*; /** Utilities for dealing with images. */ @@ -61,4 +62,65 @@ raster.setDataElements(0, image.getHeight() - i - 1, image.getWidth(), 1, scanline1); } } + + /** + * Creates a BufferedImage with a pixel format compatible with the graphics + * environment. The returned image can thus benefit from hardware accelerated operations + * in Java2D API. + * + * @param width The width of the image to be created + * @param height The height of the image to be created + * + * @return A instance of BufferedImage with a type compatible with the graphics card. + */ + public static BufferedImage createCompatibleImage(int width, int height) { + GraphicsConfiguration configuration = + GraphicsEnvironment.getLocalGraphicsEnvironment(). + getDefaultScreenDevice().getDefaultConfiguration(); + return configuration.createCompatibleImage(width, height); + } + + /** + * Creates a thumbnail from an image. A thumbnail is a scaled down version of the original picture. + * This method will retain the width to height ratio of the original picture and return a new + * instance of BufferedImage. The original picture is not modified. + * + * @param image The original image to sample down + * @param thumbWidth The width of the thumbnail to be created + * + * @throws IllegalArgumentException If thumbWidth is greater than image.getWidth() + * + * @return A thumbnail with the requested width or the original picture if thumbWidth = image.getWidth() + */ + public static BufferedImage createThumbnail(BufferedImage image, int thumbWidth) { + if (thumbWidth > image.getWidth()) { + throw new IllegalArgumentException("Thumbnail width must be greater than image width"); + } + + if (thumbWidth == image.getWidth()) { + return image; + } + + float ratio = (float) image.getWidth() / (float) image.getHeight(); + int width = image.getWidth(); + BufferedImage thumb = image; + + do { + width /= 2; + if (width < thumbWidth) { + width = thumbWidth; + } + + BufferedImage temp = createCompatibleImage(width, (int) (width / ratio)); + Graphics2D g2 = temp.createGraphics(); + g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, + RenderingHints.VALUE_INTERPOLATION_BILINEAR); + g2.drawImage(thumb, 0, 0, temp.getWidth(), temp.getHeight(), null); + g2.dispose(); + + thumb = temp; + } while (width != thumbWidth); + + return thumb; + } }