diff options
Diffstat (limited to 'src/classes')
-rwxr-xr-x | src/classes/com/sun/opengl/util/ImageUtil.java | 62 |
1 files changed, 62 insertions, 0 deletions
diff --git a/src/classes/com/sun/opengl/util/ImageUtil.java b/src/classes/com/sun/opengl/util/ImageUtil.java index 1ce77fecf..f8981bd36 100755 --- a/src/classes/com/sun/opengl/util/ImageUtil.java +++ b/src/classes/com/sun/opengl/util/ImageUtil.java @@ -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 @@ public class ImageUtil { raster.setDataElements(0, image.getHeight() - i - 1, image.getWidth(), 1, scanline1); } } + + /** + * Creates a <code>BufferedImage</code> 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 <code>BufferedImage</code> 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 <code>BufferedImage</code>. 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) { + // Thanks to Romain Guy for this utility + 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; + } } |