001: /*
002: * $Id: GraphicsUtilities.java,v 1.4 2007/01/12 19:21:20 gfx Exp $
003: *
004: * Dual-licensed under LGPL (Sun and Romain Guy) and BSD (Romain Guy).
005: *
006: * Copyright 2005 Sun Microsystems, Inc., 4150 Network Circle,
007: * Santa Clara, California 95054, U.S.A. All rights reserved.
008: *
009: * Copyright (c) 2006 Romain Guy <romain.guy@mac.com>
010: * All rights reserved.
011: *
012: * Redistribution and use in source and binary forms, with or without
013: * modification, are permitted provided that the following conditions
014: * are met:
015: * 1. Redistributions of source code must retain the above copyright
016: * notice, this list of conditions and the following disclaimer.
017: * 2. Redistributions in binary form must reproduce the above copyright
018: * notice, this list of conditions and the following disclaimer in the
019: * documentation and/or other materials provided with the distribution.
020: * 3. The name of the author may not be used to endorse or promote products
021: * derived from this software without specific prior written permission.
022: *
023: * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
024: * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
025: * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
026: * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
027: * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
028: * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
029: * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
030: * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
031: * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
032: * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
033: */
034:
035: package org.jdesktop.swingx.graphics;
036:
037: import java.awt.image.BufferedImage;
038: import java.awt.image.ColorModel;
039: import java.awt.image.Raster;
040: import java.awt.image.WritableRaster;
041: import java.awt.GraphicsConfiguration;
042: import java.awt.Transparency;
043: import java.awt.Graphics;
044: import java.awt.GraphicsEnvironment;
045: import java.awt.Graphics2D;
046: import java.awt.RenderingHints;
047: import java.io.IOException;
048: import java.net.URL;
049: import javax.imageio.ImageIO;
050:
051: /**
052: * <p><code>GraphicsUtilities</code> contains a set of tools to perform
053: * common graphics operations easily. These operations are divided into
054: * several themes, listed below.</p>
055: * <h2>Compatible Images</h2>
056: * <p>Compatible images can, and should, be used to increase drawing
057: * performance. This class provides a number of methods to load compatible
058: * images directly from files or to convert existing images to compatibles
059: * images.</p>
060: * <h2>Creating Thumbnails</h2>
061: * <p>This class provides a number of methods to easily scale down images.
062: * Some of these methods offer a trade-off between speed and result quality and
063: * shouuld be used all the time. They also offer the advantage of producing
064: * compatible images, thus automatically resulting into better runtime
065: * performance.</p>
066: * <p>All these methodes are both faster than
067: * {@link java.awt.Image#getScaledInstance(int, int, int)} and produce
068: * better-looking results than the various <code>drawImage()</code> methods
069: * in {@link java.awt.Graphics}, which can be used for image scaling.</p>
070: * <h2>Image Manipulation</h2>
071: * <p>This class provides two methods to get and set pixels in a buffered image.
072: * These methods try to avoid unmanaging the image in order to keep good
073: * performance.</p>
074: *
075: * @author Romain Guy <romain.guy@mac.com>
076: */
077: public class GraphicsUtilities {
078: private GraphicsUtilities() {
079: }
080:
081: // Returns the graphics configuration for the primary screen
082: private static GraphicsConfiguration getGraphicsConfiguration() {
083: return GraphicsEnvironment.getLocalGraphicsEnvironment()
084: .getDefaultScreenDevice().getDefaultConfiguration();
085: }
086:
087: /**
088: * <p>Returns a new <code>BufferedImage</code> using the same color model
089: * as the image passed as a parameter. The returned image is only compatible
090: * with the image passed as a parameter. This does not mean the returned
091: * image is compatible with the hardware.</p>
092: *
093: * @param image the reference image from which the color model of the new
094: * image is obtained
095: * @return a new <code>BufferedImage</code>, compatible with the color model
096: * of <code>image</code>
097: */
098: public static BufferedImage createColorModelCompatibleImage(
099: BufferedImage image) {
100: ColorModel cm = image.getColorModel();
101: return new BufferedImage(cm, cm.createCompatibleWritableRaster(
102: image.getWidth(), image.getHeight()), cm
103: .isAlphaPremultiplied(), null);
104: }
105:
106: /**
107: * <p>Returns a new compatible image with the same width, height and
108: * transparency as the image specified as a parameter.</p>
109: *
110: * @see java.awt.Transparency
111: * @see #createCompatibleImage(int, int)
112: * @see #createCompatibleImage(java.awt.image.BufferedImage, int, int)
113: * @see #createCompatibleTranslucentImage(int, int)
114: * @see #loadCompatibleImage(java.net.URL)
115: * @see #toCompatibleImage(java.awt.image.BufferedImage)
116: * @param image the reference image from which the dimension and the
117: * transparency of the new image are obtained
118: * @return a new compatible <code>BufferedImage</code> with the same
119: * dimension and transparency as <code>image</code>
120: */
121: public static BufferedImage createCompatibleImage(
122: BufferedImage image) {
123: return createCompatibleImage(image, image.getWidth(), image
124: .getHeight());
125: }
126:
127: /**
128: * <p>Returns a new compatible image of the specified width and height, and
129: * the same transparency setting as the image specified as a parameter.</p>
130: *
131: * @see java.awt.Transparency
132: * @see #createCompatibleImage(java.awt.image.BufferedImage)
133: * @see #createCompatibleImage(int, int)
134: * @see #createCompatibleTranslucentImage(int, int)
135: * @see #loadCompatibleImage(java.net.URL)
136: * @see #toCompatibleImage(java.awt.image.BufferedImage)
137: * @param width the width of the new image
138: * @param height the height of the new image
139: * @param image the reference image from which the transparency of the new
140: * image is obtained
141: * @return a new compatible <code>BufferedImage</code> with the same
142: * transparency as <code>image</code> and the specified dimension
143: */
144: public static BufferedImage createCompatibleImage(
145: BufferedImage image, int width, int height) {
146: return getGraphicsConfiguration().createCompatibleImage(width,
147: height, image.getTransparency());
148: }
149:
150: /**
151: * <p>Returns a new opaque compatible image of the specified width and
152: * height.</p>
153: *
154: * @see #createCompatibleImage(java.awt.image.BufferedImage)
155: * @see #createCompatibleImage(java.awt.image.BufferedImage, int, int)
156: * @see #createCompatibleTranslucentImage(int, int)
157: * @see #loadCompatibleImage(java.net.URL)
158: * @see #toCompatibleImage(java.awt.image.BufferedImage)
159: * @param width the width of the new image
160: * @param height the height of the new image
161: * @return a new opaque compatible <code>BufferedImage</code> of the
162: * specified width and height
163: */
164: public static BufferedImage createCompatibleImage(int width,
165: int height) {
166: return getGraphicsConfiguration().createCompatibleImage(width,
167: height);
168: }
169:
170: /**
171: * <p>Returns a new translucent compatible image of the specified width
172: * and height.</p>
173: *
174: * @see #createCompatibleImage(java.awt.image.BufferedImage)
175: * @see #createCompatibleImage(java.awt.image.BufferedImage, int, int)
176: * @see #createCompatibleImage(int, int)
177: * @see #loadCompatibleImage(java.net.URL)
178: * @see #toCompatibleImage(java.awt.image.BufferedImage)
179: * @param width the width of the new image
180: * @param height the height of the new image
181: * @return a new translucent compatible <code>BufferedImage</code> of the
182: * specified width and height
183: */
184: public static BufferedImage createCompatibleTranslucentImage(
185: int width, int height) {
186: return getGraphicsConfiguration().createCompatibleImage(width,
187: height, Transparency.TRANSLUCENT);
188: }
189:
190: /**
191: * <p>Returns a new compatible image from a URL. The image is loaded from the
192: * specified location and then turned, if necessary into a compatible
193: * image.</p>
194: *
195: * @see #createCompatibleImage(java.awt.image.BufferedImage)
196: * @see #createCompatibleImage(java.awt.image.BufferedImage, int, int)
197: * @see #createCompatibleImage(int, int)
198: * @see #createCompatibleTranslucentImage(int, int)
199: * @see #toCompatibleImage(java.awt.image.BufferedImage)
200: * @param resource the URL of the picture to load as a compatible image
201: * @return a new translucent compatible <code>BufferedImage</code> of the
202: * specified width and height
203: * @throws java.io.IOException if the image cannot be read or loaded
204: */
205: public static BufferedImage loadCompatibleImage(URL resource)
206: throws IOException {
207: BufferedImage image = ImageIO.read(resource);
208: return toCompatibleImage(image);
209: }
210:
211: /**
212: * <p>Return a new compatible image that contains a copy of the specified
213: * image. This method ensures an image is compatible with the hardware,
214: * and therefore optimized for fast blitting operations.</p>
215: *
216: * @see #createCompatibleImage(java.awt.image.BufferedImage)
217: * @see #createCompatibleImage(java.awt.image.BufferedImage, int, int)
218: * @see #createCompatibleImage(int, int)
219: * @see #createCompatibleTranslucentImage(int, int)
220: * @see #loadCompatibleImage(java.net.URL)
221: * @param image the image to copy into a new compatible image
222: * @return a new compatible copy, with the
223: * same width and height and transparency and content, of <code>image</code>
224: */
225: public static BufferedImage toCompatibleImage(BufferedImage image) {
226: if (image.getColorModel().equals(
227: getGraphicsConfiguration().getColorModel())) {
228: return image;
229: }
230:
231: BufferedImage compatibleImage = getGraphicsConfiguration()
232: .createCompatibleImage(image.getWidth(),
233: image.getHeight(), image.getTransparency());
234: Graphics g = compatibleImage.getGraphics();
235: g.drawImage(image, 0, 0, null);
236: g.dispose();
237:
238: return compatibleImage;
239: }
240:
241: /**
242: * <p>Returns a thumbnail of a source image. <code>newSize</code> defines
243: * the length of the longest dimension of the thumbnail. The other
244: * dimension is then computed according to the dimensions ratio of the
245: * original picture.</p>
246: * <p>This method favors speed over quality. When the new size is less than
247: * half the longest dimension of the source image,
248: * {@link #createThumbnail(BufferedImage, int)} or
249: * {@link #createThumbnail(BufferedImage, int, int)} should be used instead
250: * to ensure the quality of the result without sacrificing too much
251: * performance.</p>
252: *
253: * @see #createThumbnailFast(java.awt.image.BufferedImage, int, int)
254: * @see #createThumbnail(java.awt.image.BufferedImage, int)
255: * @see #createThumbnail(java.awt.image.BufferedImage, int, int)
256: * @param image the source image
257: * @param newSize the length of the largest dimension of the thumbnail
258: * @return a new compatible <code>BufferedImage</code> containing a
259: * thumbnail of <code>image</code>
260: * @throws IllegalArgumentException if <code>newSize</code> is larger than
261: * the largest dimension of <code>image</code> or <= 0
262: */
263: public static BufferedImage createThumbnailFast(
264: BufferedImage image, int newSize) {
265: float ratio;
266: int width = image.getWidth();
267: int height = image.getHeight();
268:
269: if (width > height) {
270: if (newSize >= width) {
271: throw new IllegalArgumentException(
272: "newSize must be lower than"
273: + " the image width");
274: } else if (newSize <= 0) {
275: throw new IllegalArgumentException("newSize must"
276: + " be greater than 0");
277: }
278:
279: ratio = (float) width / (float) height;
280: width = newSize;
281: height = (int) (newSize / ratio);
282: } else {
283: if (newSize >= height) {
284: throw new IllegalArgumentException(
285: "newSize must be lower than"
286: + " the image height");
287: } else if (newSize <= 0) {
288: throw new IllegalArgumentException("newSize must"
289: + " be greater than 0");
290: }
291:
292: ratio = (float) height / (float) width;
293: height = newSize;
294: width = (int) (newSize / ratio);
295: }
296:
297: BufferedImage temp = createCompatibleImage(image, width, height);
298: Graphics2D g2 = temp.createGraphics();
299: g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
300: RenderingHints.VALUE_INTERPOLATION_BILINEAR);
301: g2.drawImage(image, 0, 0, temp.getWidth(), temp.getHeight(),
302: null);
303: g2.dispose();
304:
305: return temp;
306: }
307:
308: /**
309: * <p>Returns a thumbnail of a source image.</p>
310: * <p>This method favors speed over quality. When the new size is less than
311: * half the longest dimension of the source image,
312: * {@link #createThumbnail(BufferedImage, int)} or
313: * {@link #createThumbnail(BufferedImage, int, int)} should be used instead
314: * to ensure the quality of the result without sacrificing too much
315: * performance.</p>
316: *
317: * @see #createThumbnailFast(java.awt.image.BufferedImage, int)
318: * @see #createThumbnail(java.awt.image.BufferedImage, int)
319: * @see #createThumbnail(java.awt.image.BufferedImage, int, int)
320: * @param image the source image
321: * @param newWidth the width of the thumbnail
322: * @param newHeight the height of the thumbnail
323: * @return a new compatible <code>BufferedImage</code> containing a
324: * thumbnail of <code>image</code>
325: * @throws IllegalArgumentException if <code>newWidth</code> is larger than
326: * the width of <code>image</code> or if code>newHeight</code> is larger
327: * than the height of <code>image</code> or if one of the dimensions
328: * is <= 0
329: */
330: public static BufferedImage createThumbnailFast(
331: BufferedImage image, int newWidth, int newHeight) {
332: if (newWidth >= image.getWidth()
333: || newHeight >= image.getHeight()) {
334: throw new IllegalArgumentException(
335: "newWidth and newHeight cannot"
336: + " be greater than the image"
337: + " dimensions");
338: } else if (newWidth <= 0 || newHeight <= 0) {
339: throw new IllegalArgumentException(
340: "newWidth and newHeight must"
341: + " be greater than 0");
342: }
343:
344: BufferedImage temp = createCompatibleImage(image, newWidth,
345: newHeight);
346: Graphics2D g2 = temp.createGraphics();
347: g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
348: RenderingHints.VALUE_INTERPOLATION_BILINEAR);
349: g2.drawImage(image, 0, 0, temp.getWidth(), temp.getHeight(),
350: null);
351: g2.dispose();
352:
353: return temp;
354: }
355:
356: /**
357: * <p>Returns a thumbnail of a source image. <code>newSize</code> defines
358: * the length of the longest dimension of the thumbnail. The other
359: * dimension is then computed according to the dimensions ratio of the
360: * original picture.</p>
361: * <p>This method offers a good trade-off between speed and quality.
362: * The result looks better than
363: * {@link #createThumbnailFast(java.awt.image.BufferedImage, int)} when
364: * the new size is less than half the longest dimension of the source
365: * image, yet the rendering speed is almost similar.</p>
366: *
367: * @see #createThumbnailFast(java.awt.image.BufferedImage, int, int)
368: * @see #createThumbnailFast(java.awt.image.BufferedImage, int)
369: * @see #createThumbnail(java.awt.image.BufferedImage, int, int)
370: * @param image the source image
371: * @param newSize the length of the largest dimension of the thumbnail
372: * @return a new compatible <code>BufferedImage</code> containing a
373: * thumbnail of <code>image</code>
374: * @throws IllegalArgumentException if <code>newSize</code> is larger than
375: * the largest dimension of <code>image</code> or <= 0
376: */
377: public static BufferedImage createThumbnail(BufferedImage image,
378: int newSize) {
379: int width = image.getWidth();
380: int height = image.getHeight();
381:
382: boolean isWidthGreater = width > height;
383:
384: if (isWidthGreater) {
385: if (newSize >= width) {
386: throw new IllegalArgumentException(
387: "newSize must be lower than"
388: + " the image width");
389: }
390: } else if (newSize >= height) {
391: throw new IllegalArgumentException(
392: "newSize must be lower than" + " the image height");
393: }
394:
395: if (newSize <= 0) {
396: throw new IllegalArgumentException("newSize must"
397: + " be greater than 0");
398: }
399:
400: float ratioWH = (float) width / (float) height;
401: float ratioHW = (float) height / (float) width;
402:
403: BufferedImage thumb = image;
404:
405: do {
406: if (isWidthGreater) {
407: width /= 2;
408: if (width < newSize) {
409: width = newSize;
410: }
411: height = (int) (width / ratioWH);
412: } else {
413: height /= 2;
414: if (height < newSize) {
415: height = newSize;
416: }
417: width = (int) (height / ratioHW);
418: }
419:
420: BufferedImage temp = createCompatibleImage(image, width,
421: height);
422: Graphics2D g2 = temp.createGraphics();
423: g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
424: RenderingHints.VALUE_INTERPOLATION_BILINEAR);
425: g2.drawImage(thumb, 0, 0, temp.getWidth(),
426: temp.getHeight(), null);
427: g2.dispose();
428:
429: thumb = temp;
430: } while (newSize != (isWidthGreater ? width : height));
431:
432: return thumb;
433: }
434:
435: /**
436: * <p>Returns a thumbnail of a source image.</p>
437: * <p>This method offers a good trade-off between speed and quality.
438: * The result looks better than
439: * {@link #createThumbnailFast(java.awt.image.BufferedImage, int)} when
440: * the new size is less than half the longest dimension of the source
441: * image, yet the rendering speed is almost similar.</p>
442: *
443: * @see #createThumbnailFast(java.awt.image.BufferedImage, int)
444: * @see #createThumbnailFast(java.awt.image.BufferedImage, int, int)
445: * @see #createThumbnail(java.awt.image.BufferedImage, int)
446: * @param image the source image
447: * @param newWidth the width of the thumbnail
448: * @param newHeight the height of the thumbnail
449: * @return a new compatible <code>BufferedImage</code> containing a
450: * thumbnail of <code>image</code>
451: * @throws IllegalArgumentException if <code>newWidth</code> is larger than
452: * the width of <code>image</code> or if code>newHeight</code> is larger
453: * than the height of <code>image or if one the dimensions is not > 0</code>
454: */
455: public static BufferedImage createThumbnail(BufferedImage image,
456: int newWidth, int newHeight) {
457: int width = image.getWidth();
458: int height = image.getHeight();
459:
460: if (newWidth >= width || newHeight >= height) {
461: throw new IllegalArgumentException(
462: "newWidth and newHeight cannot"
463: + " be greater than the image"
464: + " dimensions");
465: } else if (newWidth <= 0 || newHeight <= 0) {
466: throw new IllegalArgumentException(
467: "newWidth and newHeight must"
468: + " be greater than 0");
469: }
470:
471: BufferedImage thumb = image;
472:
473: do {
474: if (width > newWidth) {
475: width /= 2;
476: if (width < newWidth) {
477: width = newWidth;
478: }
479: }
480:
481: if (height > newHeight) {
482: height /= 2;
483: if (height < newHeight) {
484: height = newHeight;
485: }
486: }
487:
488: BufferedImage temp = createCompatibleImage(image, width,
489: height);
490: Graphics2D g2 = temp.createGraphics();
491: g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
492: RenderingHints.VALUE_INTERPOLATION_BILINEAR);
493: g2.drawImage(thumb, 0, 0, temp.getWidth(),
494: temp.getHeight(), null);
495: g2.dispose();
496:
497: thumb = temp;
498: } while (width != newWidth || height != newHeight);
499:
500: return thumb;
501: }
502:
503: /**
504: * <p>Returns an array of pixels, stored as integers, from a
505: * <code>BufferedImage</code>. The pixels are grabbed from a rectangular
506: * area defined by a location and two dimensions. Calling this method on
507: * an image of type different from <code>BufferedImage.TYPE_INT_ARGB</code>
508: * and <code>BufferedImage.TYPE_INT_RGB</code> will unmanage the image.</p>
509: *
510: * @param img the source image
511: * @param x the x location at which to start grabbing pixels
512: * @param y the y location at which to start grabbing pixels
513: * @param w the width of the rectangle of pixels to grab
514: * @param h the height of the rectangle of pixels to grab
515: * @param pixels a pre-allocated array of pixels of size w*h; can be null
516: * @return <code>pixels</code> if non-null, a new array of integers
517: * otherwise
518: * @throws IllegalArgumentException is <code>pixels</code> is non-null and
519: * of length < w*h
520: */
521: public static int[] getPixels(BufferedImage img, int x, int y,
522: int w, int h, int[] pixels) {
523: if (w == 0 || h == 0) {
524: return new int[0];
525: }
526:
527: if (pixels == null) {
528: pixels = new int[w * h];
529: } else if (pixels.length < w * h) {
530: throw new IllegalArgumentException(
531: "pixels array must have a length" + " >= w*h");
532: }
533:
534: int imageType = img.getType();
535: if (imageType == BufferedImage.TYPE_INT_ARGB
536: || imageType == BufferedImage.TYPE_INT_RGB) {
537: Raster raster = img.getRaster();
538: return (int[]) raster.getDataElements(x, y, w, h, pixels);
539: }
540:
541: // Unmanages the image
542: return img.getRGB(x, y, w, h, pixels, 0, w);
543: }
544:
545: /**
546: * <p>Writes a rectangular area of pixels in the destination
547: * <code>BufferedImage</code>. Calling this method on
548: * an image of type different from <code>BufferedImage.TYPE_INT_ARGB</code>
549: * and <code>BufferedImage.TYPE_INT_RGB</code> will unmanage the image.</p>
550: *
551: * @param img the destination image
552: * @param x the x location at which to start storing pixels
553: * @param y the y location at which to start storing pixels
554: * @param w the width of the rectangle of pixels to store
555: * @param h the height of the rectangle of pixels to store
556: * @param pixels an array of pixels, stored as integers
557: * @throws IllegalArgumentException is <code>pixels</code> is non-null and
558: * of length < w*h
559: */
560: public static void setPixels(BufferedImage img, int x, int y,
561: int w, int h, int[] pixels) {
562: if (pixels == null || w == 0 || h == 0) {
563: return;
564: } else if (pixels.length < w * h) {
565: throw new IllegalArgumentException(
566: "pixels array must have a length" + " >= w*h");
567: }
568:
569: int imageType = img.getType();
570: if (imageType == BufferedImage.TYPE_INT_ARGB
571: || imageType == BufferedImage.TYPE_INT_RGB) {
572: WritableRaster raster = img.getRaster();
573: raster.setDataElements(x, y, w, h, pixels);
574: } else {
575: // Unmanages the image
576: img.setRGB(x, y, w, h, pixels, 0, w);
577: }
578: }
579: }
|