Debian Codegraph @

src/com/bulenkov/iconloader/util/Scalr.java

raw symbols SCIP
1 /**
2 * Copyright 2011 The Buzz Media, LLC
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 package com.bulenkov.iconloader.util;
18
19 import javax.imageio.ImageIO;
20 import java.awt.*;
21 import java.awt.color.ColorSpace;
22 import java.awt.geom.AffineTransform;
23 import java.awt.geom.Rectangle2D;
24 import java.awt.image.*;
25
26 /**
27 * Class used to implement performant, high-quality and intelligent image
28 * scaling and manipulation algorithms in native Java 2D.
29 * <p/>
30 * This class utilizes the Java2D "best practices" for image manipulation,
31 * ensuring that all operations (even most user-provided {@link BufferedImageOp}
32 * s) are hardware accelerated if provided by the platform and host-VM.
33 * <p/>
34 * <h3>Image Quality</h3>
35 * This class implements a few different methods for scaling an image, providing
36 * either the best-looking result, the fastest result or a balanced result
37 * between the two depending on the scaling hint provided (see {@link Method}).
38 * <p/>
39 * This class also implements an optimized version of the incremental scaling
40 * algorithm presented by Chris Campbell in his <a href="http://today.java
41 * .net/pub/a/today/2007/04/03/perils-of-image-getscaledinstance.html">Perils of
42 * Image.getScaledInstance()</a> article in order to give the best-looking image
43 * resize results (e.g. generating thumbnails that aren't blurry or jagged).
44 * <p>
45 * The results generated by imgscalr using this method, as compared to a single
46 * {@link RenderingHints#VALUE_INTERPOLATION_BICUBIC} scale operation look much
47 * better, especially when using the {@link Method#ULTRA_QUALITY} method.
48 * <p/>
49 * Only when scaling using the {@link Method#AUTOMATIC} method will this class
50 * look at the size of the image before selecting an approach to scaling the
51 * image. If {@link Method#QUALITY} is specified, the best-looking algorithm
52 * possible is always used.
53 * <p/>
54 * Minor modifications are made to Campbell's original implementation in the
55 * form of:
56 * <ol>
57 * <li>Instead of accepting a user-supplied interpolation method,
58 * {@link RenderingHints#VALUE_INTERPOLATION_BICUBIC} interpolation is always
59 * used. This was done after A/B comparison testing with large images
60 * down-scaled to thumbnail sizes showed noticeable "blurring" when BILINEAR
61 * interpolation was used. Given that Campbell's algorithm is only used in
62 * QUALITY mode when down-scaling, it was determined that the user's expectation
63 * of a much less blurry picture would require that BICUBIC be the default
64 * interpolation in order to meet the QUALITY expectation.</li>
65 * <li>After each iteration of the do-while loop that incrementally scales the
66 * source image down, an explicit effort is made to call
67 * {@link BufferedImage#flush()} on the interim temporary {@link BufferedImage}
68 * instances created by the algorithm in an attempt to ensure a more complete GC
69 * cycle by the VM when cleaning up the temporary instances (this is in addition
70 * to disposing of the temporary {@link Graphics2D} references as well).</li>
71 * <li>Extensive comments have been added to increase readability of the code.</li>
72 * <li>Variable names have been expanded to increase readability of the code.</li>
73 * </ol>
74 * <p/>
75 * <strong>NOTE</strong>: This class does not call {@link BufferedImage#flush()}
76 * on any of the <em>source images</em> passed in by calling code; it is up to
77 * the original caller to dispose of their source images when they are no longer
78 * needed so the VM can most efficiently GC them.
79 * <h3>Image Proportions</h3>
80 * All scaling operations implemented by this class maintain the proportions of
81 * the original image unless a mode of {@link Mode#FIT_EXACT} is specified; in
82 * which case the orientation and proportion of the source image is ignored and
83 * the image is stretched (if necessary) to fit the exact dimensions given.
84 * <p/>
85 * When not using {@link Mode#FIT_EXACT}, in order to maintain the
86 * proportionality of the original images, this class implements the following
87 * behavior:
88 * <ol>
89 * <li>If the image is LANDSCAPE-oriented or SQUARE, treat the
90 * <code>targetWidth</code> as the primary dimension and re-calculate the
91 * <code>targetHeight</code> regardless of what is passed in.</li>
92 * <li>If image is PORTRAIT-oriented, treat the <code>targetHeight</code> as the
93 * primary dimension and re-calculate the <code>targetWidth</code> regardless of
94 * what is passed in.</li>
95 * <li>If a {@link Mode} value of {@link Mode#FIT_TO_WIDTH} or
96 * {@link Mode#FIT_TO_HEIGHT} is passed in to the <code>resize</code> method,
97 * the image's orientation is ignored and the scaled image is fit to the
98 * preferred dimension by using the value passed in by the user for that
99 * dimension and recalculating the other (regardless of image orientation). This
100 * is useful, for example, when working with PORTRAIT oriented images that you
101 * need to all be the same width or visa-versa (e.g. showing user profile
102 * pictures in a directory listing).</li>
103 * </ol>
104 * <h3>Optimized Image Handling</h3>
105 * Java2D provides support for a number of different image types defined as
106 * <code>BufferedImage.TYPE_*</code> variables, unfortunately not all image
107 * types are supported equally in the Java2D rendering pipeline.
108 * <p/>
109 * Some more obscure image types either have poor or no support, leading to
110 * severely degraded quality and processing performance when an attempt is made
111 * by imgscalr to create a scaled instance <em>of the same type</em> as the
112 * source image. In many cases, especially when applying {@link BufferedImageOp}
113 * s, using poorly supported image types can even lead to exceptions or total
114 * corruption of the image (e.g. solid black image).
115 * <p/>
116 * imgscalr specifically accounts for and automatically hands
117 * <strong>ALL</strong> of these pain points for you internally by shuffling all
118 * images into one of two types:
119 * <ol>
120 * <li>{@link BufferedImage#TYPE_INT_RGB}</li>
121 * <li>{@link BufferedImage#TYPE_INT_ARGB}</li>
122 * </ol>
123 * depending on if the source image utilizes transparency or not. This is a
124 * recommended approach by the Java2D team for dealing with poorly (or non)
125 * supported image types. More can be read about this issue <a href=
126 * "http://www.mail-archive.com/[email protected]/msg05621.html"
127 * >here</a>.
128 * <p/>
129 * This is also the reason we recommend using
130 * {@link #apply(BufferedImage, BufferedImageOp...)} to apply your own ops to
131 * images even if you aren't using imgscalr for anything else.
132 * <h3>GIF Transparency</h3>
133 * Unfortunately in Java 6 and earlier, support for GIF's
134 * {@link IndexColorModel} is sub-par, both in accurate color-selection and in
135 * maintaining transparency when moving to an image of type
136 * {@link BufferedImage#TYPE_INT_ARGB}; because of this issue when a GIF image
137 * is processed by imgscalr and the result saved as a GIF file (instead of PNG),
138 * it is possible to lose the alpha channel of a transparent image or in the
139 * case of applying an optional {@link BufferedImageOp}, lose the entire picture
140 * all together in the result (long standing JDK bugs are filed for all of these
141 * issues).
142 * <p/>
143 * imgscalr currently does nothing to work around this manually because it is a
144 * defect in the native platform code itself. Fortunately it looks like the
145 * issues are half-fixed in Java 7 and any manual workarounds we could attempt
146 * internally are relatively expensive, in the form of hand-creating and setting
147 * RGB values pixel-by-pixel with a custom {@link ColorModel} in the scaled
148 * image. This would lead to a very measurable negative impact on performance
149 * without the caller understanding why.
150 * <p>
151 * <strong>Workaround</strong>: A workaround to this issue with all version of
152 * Java is to simply save a GIF as a PNG; no change to your code needs to be
153 * made except when the image is saved out, e.g. using {@link ImageIO}.
154 * <p>
155 * When a file type of "PNG" is used, both the transparency and high color
156 * quality will be maintained as the PNG code path in Java2D is superior to the
157 * GIF implementation.
158 * <p>
159 * If the issue with optional {@link BufferedImageOp}s destroying GIF image
160 * content is ever fixed in the platform, saving out resulting images as GIFs
161 * should suddenly start working.
162 * <p>
163 * More can be read about the issue <a
164 * href="http://gman.eichberger.de/2007/07/transparent-gifs-in-java.html"
165 * >here</a> and <a
166 * href="http://ubuntuforums.org/archive/index.php/t-1060128.html">here</a>.
167 * <h3>Thread Safety</h3>
168 * The {@link Scalr} class is <strong>thread-safe</strong> (as all the methods
169 * are <code>static</code>); this class maintains no internal state while
170 * performing any of the provided operations and is safe to call simultaneously
171 * from multiple threads.
172 * <h3>Logging</h3>
173 * This class implements all its debug logging via the
174 * {@link #log(int, String, Object...)} method. At this time logging is done
175 * directly to <code>System.out</code> via the <code>printf</code> method. This
176 * allows the logging to be light weight and easy to capture (every imgscalr log
177 * message is prefixed with the {@link #LOG_PREFIX} string) while adding no
178 * dependencies to the library.
179 * <p/>
180 * Implementation of logging in this class is as efficient as possible; avoiding
181 * any calls to the logger method or passing of arguments if logging is not
182 * enabled to avoid the (hidden) cost of constructing the Object[] argument for
183 * the varargs-based method call.
184 *
185 * @author Riyad Kalla ([email protected])
186 * @since 1.1
187 */
188 public class Scalr {
189 /**
190 * System property name used to define the debug boolean flag.
191 * <p/>
192 * Value is "<code>imgscalr.debug</code>".
193 */
194 public static final String DEBUG_PROPERTY_NAME = "imgscalr.debug";
195
196 /**
197 * System property name used to define a custom log prefix.
198 * <p/>
199 * Value is "<code>imgscalr.logPrefix</code>".
200 */
201 public static final String LOG_PREFIX_PROPERTY_NAME = "imgscalr.logPrefix";
202
203 /**
204 * Flag used to indicate if debugging output has been enabled by setting the
205 * "<code>imgscalr.debug</code>" system property to <code>true</code>. This
206 * value will be <code>false</code> if the "<code>imgscalr.debug</code>"
207 * system property is undefined or set to <code>false</code>.
208 * <p/>
209 * This property can be set on startup with:<br/>
210 * <code>
211 * -Dimgscalr.debug=true
212 * </code> or by calling {@link System#setProperty(String, String)} to set a
213 * new property value for {@link #DEBUG_PROPERTY_NAME} before this class is
214 * loaded.
215 * <p/>
216 * Default value is <code>false</code>.
217 */
218 public static final boolean DEBUG = Boolean.getBoolean(DEBUG_PROPERTY_NAME);
219
220 /**
221 * Prefix to every log message this library logs. Using a well-defined
222 * prefix helps make it easier both visually and programmatically to scan
223 * log files for messages produced by this library.
224 * <p/>
225 * This property can be set on startup with:<br/>
226 * <code>
227 * -Dimgscalr.logPrefix=&lt;YOUR PREFIX HERE&gt;
228 * </code> or by calling {@link System#setProperty(String, String)} to set a
229 * new property value for {@link #LOG_PREFIX_PROPERTY_NAME} before this
230 * class is loaded.
231 * <p/>
232 * Default value is "<code>[imgscalr] </code>" (including the space).
233 */
234 public static final String LOG_PREFIX = System.getProperty(
235 LOG_PREFIX_PROPERTY_NAME, "[imgscalr] ");
236
237 /**
238 * A {@link ConvolveOp} using a very light "blur" kernel that acts like an
239 * anti-aliasing filter (softens the image a bit) when applied to an image.
240 * <p/>
241 * A common request by users of the library was that they wished to "soften"
242 * resulting images when scaling them down drastically. After quite a bit of
243 * A/B testing, the kernel used by this Op was selected as the closest match
244 * for the target which was the softer results from the deprecated
245 * {@link AreaAveragingScaleFilter} (which is used internally by the
246 * deprecated {@link Image#getScaledInstance(int, int, int)} method in the
247 * JDK that imgscalr is meant to replace).
248 * <p/>
249 * This ConvolveOp uses a 3x3 kernel with the values:
250 * <table cellpadding="4" border="1">
251 * <tr>
252 * <td>.0f</td>
253 * <td>.08f</td>
254 * <td>.0f</td>
255 * </tr>
256 * <tr>
257 * <td>.08f</td>
258 * <td>.68f</td>
259 * <td>.08f</td>
260 * </tr>
261 * <tr>
262 * <td>.0f</td>
263 * <td>.08f</td>
264 * <td>.0f</td>
265 * </tr>
266 * </table>
267 * <p/>
268 * For those that have worked with ConvolveOps before, this Op uses the
269 * {@link ConvolveOp#EDGE_NO_OP} instruction to not process the pixels along
270 * the very edge of the image (otherwise EDGE_ZERO_FILL would create a
271 * black-border around the image). If you have not worked with a ConvolveOp
272 * before, it just means this default OP will "do the right thing" and not
273 * give you garbage results.
274 * <p/>
275 * This ConvolveOp uses no {@link RenderingHints} values as internally the
276 * {@link ConvolveOp} class only uses hints when doing a color conversion
277 * between the source and destination {@link BufferedImage} targets.
278 * imgscalr allows the {@link ConvolveOp} to create its own destination
279 * image every time, so no color conversion is ever needed and thus no
280 * hints.
281 * <h3>Performance</h3>
282 * Use of this (and other) {@link ConvolveOp}s are hardware accelerated when
283 * possible. For more information on if your image op is hardware
284 * accelerated or not, check the source code of the underlying JDK class
285 * that actually executes the Op code, <a href=
286 * "http://www.docjar.com/html/api/sun/awt/image/ImagingLib.java.html"
287 * >sun.awt.image.ImagingLib</a>.
288 * <h3>Known Issues</h3>
289 * In all versions of Java (tested up to Java 7 preview Build 131), running
290 * this op against a GIF with transparency and attempting to save the
291 * resulting image as a GIF results in a corrupted/empty file. The file must
292 * be saved out as a PNG to maintain the transparency.
293 *
294 * @since 3.0
295 */
296 public static final ConvolveOp OP_ANTIALIAS = new ConvolveOp(
297 new Kernel(3, 3, new float[] { .0f, .08f, .0f, .08f, .68f, .08f,
298 .0f, .08f, .0f }), ConvolveOp.EDGE_NO_OP, null);
299
300 /**
301 * A {@link RescaleOp} used to make any input image 10% darker.
302 * <p/>
303 * This operation can be applied multiple times in a row if greater than 10%
304 * changes in brightness are desired.
305 *
306 * @since 4.0
307 */
308 public static final RescaleOp OP_DARKER = new RescaleOp(0.9f, 0, null);
309
310 /**
311 * A {@link RescaleOp} used to make any input image 10% brighter.
312 * <p/>
313 * This operation can be applied multiple times in a row if greater than 10%
314 * changes in brightness are desired.
315 *
316 * @since 4.0
317 */
318 public static final RescaleOp OP_BRIGHTER = new RescaleOp(1.1f, 0, null);
319
320 /**
321 * A {@link ColorConvertOp} used to convert any image to a grayscale color
322 * palette.
323 * <p/>
324 * Applying this op multiple times to the same image has no compounding
325 * effects.
326 *
327 * @since 4.0
328 */
329 public static final ColorConvertOp OP_GRAYSCALE = new ColorConvertOp(
330 ColorSpace.getInstance(ColorSpace.CS_GRAY), null);
331
332 /**
333 * Static initializer used to prepare some of the variables used by this
334 * class.
335 */
336 static {
337 log(0, "Debug output ENABLED");
338 }
339
340 /**
341 * Used to define the different scaling hints that the algorithm can use.
342 *
343 * @author Riyad Kalla ([email protected])
344 * @since 1.1
345 */
346 public static enum Method {
347 /**
348 * Used to indicate that the scaling implementation should decide which
349 * method to use in order to get the best looking scaled image in the
350 * least amount of time.
351 * <p/>
352 * The scaling algorithm will use the
353 * {@link Scalr#THRESHOLD_QUALITY_BALANCED} or
354 * {@link Scalr#THRESHOLD_BALANCED_SPEED} thresholds as cut-offs to
355 * decide between selecting the <code>QUALITY</code>,
356 * <code>BALANCED</code> or <code>SPEED</code> scaling algorithms.
357 * <p/>
358 * By default the thresholds chosen will give nearly the best looking
359 * result in the fastest amount of time. We intend this method to work
360 * for 80% of people looking to scale an image quickly and get a good
361 * looking result.
362 */
363 AUTOMATIC,
364 /**
365 * Used to indicate that the scaling implementation should scale as fast
366 * as possible and return a result. For smaller images (800px in size)
367 * this can result in noticeable aliasing but it can be a few magnitudes
368 * times faster than using the QUALITY method.
369 */
370 SPEED,
371 /**
372 * Used to indicate that the scaling implementation should use a scaling
373 * operation balanced between SPEED and QUALITY. Sometimes SPEED looks
374 * too low quality to be useful (e.g. text can become unreadable when
375 * scaled using SPEED) but using QUALITY mode will increase the
376 * processing time too much. This mode provides a "better than SPEED"
377 * quality in a "less than QUALITY" amount of time.
378 */
379 BALANCED,
380 /**
381 * Used to indicate that the scaling implementation should do everything
382 * it can to create as nice of a result as possible. This approach is
383 * most important for smaller pictures (800px or smaller) and less
384 * important for larger pictures as the difference between this method
385 * and the SPEED method become less and less noticeable as the
386 * source-image size increases. Using the AUTOMATIC method will
387 * automatically prefer the QUALITY method when scaling an image down
388 * below 800px in size.
389 */
390 QUALITY,
391 /**
392 * Used to indicate that the scaling implementation should go above and
393 * beyond the work done by {@link Method#QUALITY} to make the image look
394 * exceptionally good at the cost of more processing time. This is
395 * especially evident when generating thumbnails of images that look
396 * jagged with some of the other {@link Method}s (even
397 * {@link Method#QUALITY}).
398 */
399 ULTRA_QUALITY;
400 }
401
402 /**
403 * Used to define the different modes of resizing that the algorithm can
404 * use.
405 *
406 * @author Riyad Kalla ([email protected])
407 * @since 3.1
408 */
409 public static enum Mode {
410 /**
411 * Used to indicate that the scaling implementation should calculate
412 * dimensions for the resultant image by looking at the image's
413 * orientation and generating proportional dimensions that best fit into
414 * the target width and height given
415 *
416 * See "Image Proportions" in the {@link Scalr} class description for
417 * more detail.
418 */
419 AUTOMATIC,
420 /**
421 * Used to fit the image to the exact dimensions given regardless of the
422 * image's proportions. If the dimensions are not proportionally
423 * correct, this will introduce vertical or horizontal stretching to the
424 * image.
425 * <p/>
426 * It is recommended that you use one of the other <code>FIT_TO</code>
427 * modes or {@link Mode#AUTOMATIC} if you want the image to look
428 * correct, but if dimension-fitting is the #1 priority regardless of
429 * how it makes the image look, that is what this mode is for.
430 */
431 FIT_EXACT,
432 /**
433 * Used to indicate that the scaling implementation should calculate
434 * dimensions for the resultant image that best-fit within the given
435 * width, regardless of the orientation of the image.
436 */
437 FIT_TO_WIDTH,
438 /**
439 * Used to indicate that the scaling implementation should calculate
440 * dimensions for the resultant image that best-fit within the given
441 * height, regardless of the orientation of the image.
442 */
443 FIT_TO_HEIGHT;
444 }
445
446 /**
447 * Used to define the different types of rotations that can be applied to an
448 * image during a resize operation.
449 *
450 * @author Riyad Kalla ([email protected])
451 * @since 3.2
452 */
453 public static enum Rotation {
454 /**
455 * 90-degree, clockwise rotation (to the right). This is equivalent to a
456 * quarter-turn of the image to the right; moving the picture on to its
457 * right side.
458 */
459 CW_90,
460 /**
461 * 180-degree, clockwise rotation (to the right). This is equivalent to
462 * 1 half-turn of the image to the right; rotating the picture around
463 * until it is upside down from the original position.
464 */
465 CW_180,
466 /**
467 * 270-degree, clockwise rotation (to the right). This is equivalent to
468 * a quarter-turn of the image to the left; moving the picture on to its
469 * left side.
470 */
471 CW_270,
472 /**
473 * Flip the image horizontally by reflecting it around the y axis.
474 * <p/>
475 * This is not a standard rotation around a center point, but instead
476 * creates the mirrored reflection of the image horizontally.
477 * <p/>
478 * More specifically, the vertical orientation of the image stays the
479 * same (the top stays on top, and the bottom on bottom), but the right
480 * and left sides flip. This is different than a standard rotation where
481 * the top and bottom would also have been flipped.
482 */
483 FLIP_HORZ,
484 /**
485 * Flip the image vertically by reflecting it around the x axis.
486 * <p/>
487 * This is not a standard rotation around a center point, but instead
488 * creates the mirrored reflection of the image vertically.
489 * <p/>
490 * More specifically, the horizontal orientation of the image stays the
491 * same (the left stays on the left and the right stays on the right),
492 * but the top and bottom sides flip. This is different than a standard
493 * rotation where the left and right would also have been flipped.
494 */
495 FLIP_VERT;
496 }
497
498 /**
499 * Threshold (in pixels) at which point the scaling operation using the
500 * {@link Method#AUTOMATIC} method will decide if a {@link Method#BALANCED}
501 * method will be used (if smaller than or equal to threshold) or a
502 * {@link Method#SPEED} method will be used (if larger than threshold).
503 * <p/>
504 * The bigger the image is being scaled to, the less noticeable degradations
505 * in the image becomes and the faster algorithms can be selected.
506 * <p/>
507 * The value of this threshold (1600) was chosen after visual, by-hand, A/B
508 * testing between different types of images scaled with this library; both
509 * photographs and screenshots. It was determined that images below this
510 * size need to use a {@link Method#BALANCED} scale method to look decent in
511 * most all cases while using the faster {@link Method#SPEED} method for
512 * images bigger than this threshold showed no noticeable degradation over a
513 * <code>BALANCED</code> scale.
514 */
515 public static final int THRESHOLD_BALANCED_SPEED = 1600;
516
517 /**
518 * Threshold (in pixels) at which point the scaling operation using the
519 * {@link Method#AUTOMATIC} method will decide if a {@link Method#QUALITY}
520 * method will be used (if smaller than or equal to threshold) or a
521 * {@link Method#BALANCED} method will be used (if larger than threshold).
522 * <p/>
523 * The bigger the image is being scaled to, the less noticeable degradations
524 * in the image becomes and the faster algorithms can be selected.
525 * <p/>
526 * The value of this threshold (800) was chosen after visual, by-hand, A/B
527 * testing between different types of images scaled with this library; both
528 * photographs and screenshots. It was determined that images below this
529 * size need to use a {@link Method#QUALITY} scale method to look decent in
530 * most all cases while using the faster {@link Method#BALANCED} method for
531 * images bigger than this threshold showed no noticeable degradation over a
532 * <code>QUALITY</code> scale.
533 */
534 public static final int THRESHOLD_QUALITY_BALANCED = 800;
535
536 /**
537 * Used to apply, in the order given, 1 or more {@link BufferedImageOp}s to
538 * a given {@link BufferedImage} and return the result.
539 * <p/>
540 * <strong>Feature</strong>: This implementation works around <a
541 * href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4965606">a
542 * decade-old JDK bug</a> that can cause a {@link RasterFormatException}
543 * when applying a perfectly valid {@link BufferedImageOp}s to images.
544 * <p/>
545 * <strong>Feature</strong>: This implementation also works around
546 * {@link BufferedImageOp}s failing to apply and throwing
547 * {@link ImagingOpException}s when run against a <code>src</code> image
548 * type that is poorly supported. Unfortunately using {@link ImageIO} and
549 * standard Java methods to load images provides no consistency in getting
550 * images in well-supported formats. This method automatically accounts and
551 * corrects for all those problems (if necessary).
552 * <p/>
553 * It is recommended you always use this method to apply any
554 * {@link BufferedImageOp}s instead of relying on directly using the
555 * {@link BufferedImageOp#filter(BufferedImage, BufferedImage)} method.
556 * <p/>
557 * <strong>Performance</strong>: Not all {@link BufferedImageOp}s are
558 * hardware accelerated operations, but many of the most popular (like
559 * {@link ConvolveOp}) are. For more information on if your image op is
560 * hardware accelerated or not, check the source code of the underlying JDK
561 * class that actually executes the Op code, <a href=
562 * "http://www.docjar.com/html/api/sun/awt/image/ImagingLib.java.html"
563 * >sun.awt.image.ImagingLib</a>.
564 * <p/>
565 * <strong>TIP</strong>: This operation leaves the original <code>src</code>
566 * image unmodified. If the caller is done with the <code>src</code> image
567 * after getting the result of this operation, remember to call
568 * {@link BufferedImage#flush()} on the <code>src</code> to free up native
569 * resources and make it easier for the GC to collect the unused image.
570 *
571 * @param src
572 * The image that will have the ops applied to it.
573 * @param ops
574 * <code>1</code> or more ops to apply to the image.
575 *
576 * @return a new {@link BufferedImage} that represents the <code>src</code>
577 * with all the given operations applied to it.
578 *
579 * @throws IllegalArgumentException
580 * if <code>src</code> is <code>null</code>.
581 * @throws IllegalArgumentException
582 * if <code>ops</code> is <code>null</code> or empty.
583 * @throws ImagingOpException
584 * if one of the given {@link BufferedImageOp}s fails to apply.
585 * These exceptions bubble up from the inside of most of the
586 * {@link BufferedImageOp} implementations and are explicitly
587 * defined on the imgscalr API to make it easier for callers to
588 * catch the exception (if they are passing along optional ops
589 * to be applied). imgscalr takes detailed steps to avoid the
590 * most common pitfalls that will cause {@link BufferedImageOp}s
591 * to fail, even when using straight forward JDK-image
592 * operations.
593 */
594 public static BufferedImage apply(BufferedImage src, BufferedImageOp... ops)
595 throws IllegalArgumentException, ImagingOpException {
596 long t = System.currentTimeMillis();
597
598 if (src == null)
599 throw new IllegalArgumentException("src cannot be null");
600 if (ops == null || ops.length == 0)
601 throw new IllegalArgumentException("ops cannot be null or empty");
602
603 int type = src.getType();
604
605 /*
606 * Ensure the src image is in the best supported image type before we
607 * continue, otherwise it is possible our calls below to getBounds2D and
608 * certainly filter(...) may fail if not.
609 *
610 * Java2D makes an attempt at applying most BufferedImageOps using
611 * hardware acceleration via the ImagingLib internal library.
612 *
613 * Unfortunately may of the BufferedImageOp are written to simply fail
614 * with an ImagingOpException if the operation cannot be applied with no
615 * additional information about what went wrong or attempts at
616 * re-applying it in different ways.
617 *
618 * This is assuming the failing BufferedImageOp even returns a null
619 * image after failing to apply; some simply return a corrupted/black
620 * image that result in no exception and it is up to the user to
621 * discover this.
622 *
623 * In internal testing, EVERY failure I've ever seen was the result of
624 * the source image being in a poorly-supported BufferedImage Type like
625 * BGR or ABGR (even though it was loaded with ImageIO).
626 *
627 * To avoid this nasty/stupid surprise with BufferedImageOps, we always
628 * ensure that the src image starts in an optimally supported format
629 * before we try and apply the filter.
630 */
631 if (!(type == BufferedImage.TYPE_INT_RGB || type == BufferedImage.TYPE_INT_ARGB))
632 src = copyToOptimalImage(src);
633
634 if (DEBUG)
635 log(0, "Applying %d BufferedImageOps...", ops.length);
636
637 boolean hasReassignedSrc = false;
638
639 for (int i = 0; i < ops.length; i++) {
640 long subT = System.currentTimeMillis();
641 BufferedImageOp op = ops[i];
642
643 // Skip null ops instead of throwing an exception.
644 if (op == null)
645 continue;
646
647 if (DEBUG)
648 log(1, "Applying BufferedImageOp [class=%s, toString=%s]...",
649 op.getClass(), op.toString());
650
651 /*
652 * Must use op.getBounds instead of src.getWidth and src.getHeight
653 * because we are trying to create an image big enough to hold the
654 * result of this operation (which may be to scale the image
655 * smaller), in that case the bounds reported by this op and the
656 * bounds reported by the source image will be different.
657 */
658 Rectangle2D resultBounds = op.getBounds2D(src);
659
660 // Watch out for flaky/misbehaving ops that fail to work right.
661 if (resultBounds == null)
662 throw new ImagingOpException(
663 "BufferedImageOp ["
664 + op.toString()
665 + "] getBounds2D(src) returned null bounds for the target image; this should not happen and indicates a problem with application of this type of op.");
666
667 /*
668 * We must manually create the target image; we cannot rely on the
669 * null-destination filter() method to create a valid destination
670 * for us thanks to this JDK bug that has been filed for almost a
671 * decade:
672 * http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4965606
673 */
674 BufferedImage dest = createOptimalImage(src,
675 (int) Math.round(resultBounds.getWidth()),
676 (int) Math.round(resultBounds.getHeight()));
677
678 // Perform the operation, update our result to return.
679 BufferedImage result = op.filter(src, dest);
680
681 /*
682 * Flush the 'src' image ONLY IF it is one of our interim temporary
683 * images being used when applying 2 or more operations back to
684 * back. We never want to flush the original image passed in.
685 */
686 if (hasReassignedSrc)
687 src.flush();
688
689 /*
690 * Incase there are more operations to perform, update what we
691 * consider the 'src' reference to our last result so on the next
692 * iteration the next op is applied to this result and not back
693 * against the original src passed in.
694 */
695 src = result;
696
697 /*
698 * Keep track of when we re-assign 'src' to an interim temporary
699 * image, so we know when we can explicitly flush it and clean up
700 * references on future iterations.
701 */
702 hasReassignedSrc = true;
703
704 if (DEBUG)
705 log(1,
706 "Applied BufferedImageOp in %d ms, result [width=%d, height=%d]",
707 System.currentTimeMillis() - subT, result.getWidth(),
708 result.getHeight());
709 }
710
711 if (DEBUG)
712 log(0, "All %d BufferedImageOps applied in %d ms", ops.length,
713 System.currentTimeMillis() - t);
714
715 return src;
716 }
717
718 /**
719 * Used to crop the given <code>src</code> image from the top-left corner
720 * and applying any optional {@link BufferedImageOp}s to the result before
721 * returning it.
722 * <p/>
723 * <strong>TIP</strong>: This operation leaves the original <code>src</code>
724 * image unmodified. If the caller is done with the <code>src</code> image
725 * after getting the result of this operation, remember to call
726 * {@link BufferedImage#flush()} on the <code>src</code> to free up native
727 * resources and make it easier for the GC to collect the unused image.
728 *
729 * @param src
730 * The image to crop.
731 * @param width
732 * The width of the bounding cropping box.
733 * @param height
734 * The height of the bounding cropping box.
735 * @param ops
736 * <code>0</code> or more ops to apply to the image. If
737 * <code>null</code> or empty then <code>src</code> is return
738 * unmodified.
739 *
740 * @return a new {@link BufferedImage} representing the cropped region of
741 * the <code>src</code> image with any optional operations applied
742 * to it.
743 *
744 * @throws IllegalArgumentException
745 * if <code>src</code> is <code>null</code>.
746 * @throws IllegalArgumentException
747 * if any coordinates of the bounding crop box is invalid within
748 * the bounds of the <code>src</code> image (e.g. negative or
749 * too big).
750 * @throws ImagingOpException
751 * if one of the given {@link BufferedImageOp}s fails to apply.
752 * These exceptions bubble up from the inside of most of the
753 * {@link BufferedImageOp} implementations and are explicitly
754 * defined on the imgscalr API to make it easier for callers to
755 * catch the exception (if they are passing along optional ops
756 * to be applied). imgscalr takes detailed steps to avoid the
757 * most common pitfalls that will cause {@link BufferedImageOp}s
758 * to fail, even when using straight forward JDK-image
759 * operations.
760 */
761 public static BufferedImage crop(BufferedImage src, int width, int height,
762 BufferedImageOp... ops) throws IllegalArgumentException,
763 ImagingOpException {
764 return crop(src, 0, 0, width, height, ops);
765 }
766
767 /**
768 * Used to crop the given <code>src</code> image and apply any optional
769 * {@link BufferedImageOp}s to it before returning the result.
770 * <p/>
771 * <strong>TIP</strong>: This operation leaves the original <code>src</code>
772 * image unmodified. If the caller is done with the <code>src</code> image
773 * after getting the result of this operation, remember to call
774 * {@link BufferedImage#flush()} on the <code>src</code> to free up native
775 * resources and make it easier for the GC to collect the unused image.
776 *
777 * @param src
778 * The image to crop.
779 * @param x
780 * The x-coordinate of the top-left corner of the bounding box
781 * used for cropping.
782 * @param y
783 * The y-coordinate of the top-left corner of the bounding box
784 * used for cropping.
785 * @param width
786 * The width of the bounding cropping box.
787 * @param height
788 * The height of the bounding cropping box.
789 * @param ops
790 * <code>0</code> or more ops to apply to the image. If
791 * <code>null</code> or empty then <code>src</code> is return
792 * unmodified.
793 *
794 * @return a new {@link BufferedImage} representing the cropped region of
795 * the <code>src</code> image with any optional operations applied
796 * to it.
797 *
798 * @throws IllegalArgumentException
799 * if <code>src</code> is <code>null</code>.
800 * @throws IllegalArgumentException
801 * if any coordinates of the bounding crop box is invalid within
802 * the bounds of the <code>src</code> image (e.g. negative or
803 * too big).
804 * @throws ImagingOpException
805 * if one of the given {@link BufferedImageOp}s fails to apply.
806 * These exceptions bubble up from the inside of most of the
807 * {@link BufferedImageOp} implementations and are explicitly
808 * defined on the imgscalr API to make it easier for callers to
809 * catch the exception (if they are passing along optional ops
810 * to be applied). imgscalr takes detailed steps to avoid the
811 * most common pitfalls that will cause {@link BufferedImageOp}s
812 * to fail, even when using straight forward JDK-image
813 * operations.
814 */
815 public static BufferedImage crop(BufferedImage src, int x, int y,
816 int width, int height, BufferedImageOp... ops)
817 throws IllegalArgumentException, ImagingOpException {
818 long t = System.currentTimeMillis();
819
820 if (src == null)
821 throw new IllegalArgumentException("src cannot be null");
822 if (x < 0 || y < 0 || width < 0 || height < 0)
823 throw new IllegalArgumentException("Invalid crop bounds: x [" + x
824 + "], y [" + y + "], width [" + width + "] and height ["
825 + height + "] must all be >= 0");
826
827 int srcWidth = src.getWidth();
828 int srcHeight = src.getHeight();
829
830 if ((x + width) > srcWidth)
831 throw new IllegalArgumentException(
832 "Invalid crop bounds: x + width [" + (x + width)
833 + "] must be <= src.getWidth() [" + srcWidth + "]");
834 if ((y + height) > srcHeight)
835 throw new IllegalArgumentException(
836 "Invalid crop bounds: y + height [" + (y + height)
837 + "] must be <= src.getHeight() [" + srcHeight
838 + "]");
839
840 if (DEBUG)
841 log(0,
842 "Cropping Image [width=%d, height=%d] to [x=%d, y=%d, width=%d, height=%d]...",
843 srcWidth, srcHeight, x, y, width, height);
844
845 // Create a target image of an optimal type to render into.
846 BufferedImage result = createOptimalImage(src, width, height);
847 Graphics g = result.getGraphics();
848
849 /*
850 * Render the region specified by our crop bounds from the src image
851 * directly into our result image (which is the exact size of the crop
852 * region).
853 */
854 g.drawImage(src, 0, 0, width, height, x, y, (x + width), (y + height),
855 null);
856 g.dispose();
857
858 if (DEBUG)
859 log(0, "Cropped Image in %d ms", System.currentTimeMillis() - t);
860
861 // Apply any optional operations (if specified).
862 if (ops != null && ops.length > 0)
863 result = apply(result, ops);
864
865 return result;
866 }
867
868 /**
869 * Used to apply padding around the edges of an image using
870 * {@link Color#BLACK} to fill the extra padded space and then return the
871 * result.
872 * <p/>
873 * The amount of <code>padding</code> specified is applied to all sides;
874 * more specifically, a <code>padding</code> of <code>2</code> would add 2
875 * extra pixels of space (filled by the given <code>color</code>) on the
876 * top, bottom, left and right sides of the resulting image causing the
877 * result to be 4 pixels wider and 4 pixels taller than the <code>src</code>
878 * image.
879 * <p/>
880 * <strong>TIP</strong>: This operation leaves the original <code>src</code>
881 * image unmodified. If the caller is done with the <code>src</code> image
882 * after getting the result of this operation, remember to call
883 * {@link BufferedImage#flush()} on the <code>src</code> to free up native
884 * resources and make it easier for the GC to collect the unused image.
885 *
886 * @param src
887 * The image the padding will be added to.
888 * @param padding
889 * The number of pixels of padding to add to each side in the
890 * resulting image. If this value is <code>0</code> then
891 * <code>src</code> is returned unmodified.
892 * @param ops
893 * <code>0</code> or more ops to apply to the image. If
894 * <code>null</code> or empty then <code>src</code> is return
895 * unmodified.
896 *
897 * @return a new {@link BufferedImage} representing <code>src</code> with
898 * the given padding applied to it.
899 *
900 * @throws IllegalArgumentException
901 * if <code>src</code> is <code>null</code>.
902 * @throws IllegalArgumentException
903 * if <code>padding</code> is &lt; <code>1</code>.
904 * @throws ImagingOpException
905 * if one of the given {@link BufferedImageOp}s fails to apply.
906 * These exceptions bubble up from the inside of most of the
907 * {@link BufferedImageOp} implementations and are explicitly
908 * defined on the imgscalr API to make it easier for callers to
909 * catch the exception (if they are passing along optional ops
910 * to be applied). imgscalr takes detailed steps to avoid the
911 * most common pitfalls that will cause {@link BufferedImageOp}s
912 * to fail, even when using straight forward JDK-image
913 * operations.
914 */
915 public static BufferedImage pad(BufferedImage src, int padding,
916 BufferedImageOp... ops) throws IllegalArgumentException,
917 ImagingOpException {
918 return pad(src, padding, Color.BLACK);
919 }
920
921 /**
922 * Used to apply padding around the edges of an image using the given color
923 * to fill the extra padded space and then return the result. {@link Color}s
924 * using an alpha channel (i.e. transparency) are supported.
925 * <p/>
926 * The amount of <code>padding</code> specified is applied to all sides;
927 * more specifically, a <code>padding</code> of <code>2</code> would add 2
928 * extra pixels of space (filled by the given <code>color</code>) on the
929 * top, bottom, left and right sides of the resulting image causing the
930 * result to be 4 pixels wider and 4 pixels taller than the <code>src</code>
931 * image.
932 * <p/>
933 * <strong>TIP</strong>: This operation leaves the original <code>src</code>
934 * image unmodified. If the caller is done with the <code>src</code> image
935 * after getting the result of this operation, remember to call
936 * {@link BufferedImage#flush()} on the <code>src</code> to free up native
937 * resources and make it easier for the GC to collect the unused image.
938 *
939 * @param src
940 * The image the padding will be added to.
941 * @param padding
942 * The number of pixels of padding to add to each side in the
943 * resulting image. If this value is <code>0</code> then
944 * <code>src</code> is returned unmodified.
945 * @param color
946 * The color to fill the padded space with. {@link Color}s using
947 * an alpha channel (i.e. transparency) are supported.
948 * @param ops
949 * <code>0</code> or more ops to apply to the image. If
950 * <code>null</code> or empty then <code>src</code> is return
951 * unmodified.
952 *
953 * @return a new {@link BufferedImage} representing <code>src</code> with
954 * the given padding applied to it.
955 *
956 * @throws IllegalArgumentException
957 * if <code>src</code> is <code>null</code>.
958 * @throws IllegalArgumentException
959 * if <code>padding</code> is &lt; <code>1</code>.
960 * @throws IllegalArgumentException
961 * if <code>color</code> is <code>null</code>.
962 * @throws ImagingOpException
963 * if one of the given {@link BufferedImageOp}s fails to apply.
964 * These exceptions bubble up from the inside of most of the
965 * {@link BufferedImageOp} implementations and are explicitly
966 * defined on the imgscalr API to make it easier for callers to
967 * catch the exception (if they are passing along optional ops
968 * to be applied). imgscalr takes detailed steps to avoid the
969 * most common pitfalls that will cause {@link BufferedImageOp}s
970 * to fail, even when using straight forward JDK-image
971 * operations.
972 */
973 public static BufferedImage pad(BufferedImage src, int padding,
974 Color color, BufferedImageOp... ops)
975 throws IllegalArgumentException, ImagingOpException {
976 long t = System.currentTimeMillis();
977
978 if (src == null)
979 throw new IllegalArgumentException("src cannot be null");
980 if (padding < 1)
981 throw new IllegalArgumentException("padding [" + padding
982 + "] must be > 0");
983 if (color == null)
984 throw new IllegalArgumentException("color cannot be null");
985
986 int srcWidth = src.getWidth();
987 int srcHeight = src.getHeight();
988
989 /*
990 * Double the padding to account for all sides of the image. More
991 * specifically, if padding is "1" we add 2 pixels to width and 2 to
992 * height, so we have 1 new pixel of padding all the way around our
993 * image.
994 */
995 int sizeDiff = (padding * 2);
996 int newWidth = srcWidth + sizeDiff;
997 int newHeight = srcHeight + sizeDiff;
998
999 if (DEBUG)
1000 log(0,
1001 "Padding Image from [originalWidth=%d, originalHeight=%d, padding=%d] to [newWidth=%d, newHeight=%d]...",
1002 srcWidth, srcHeight, padding, newWidth, newHeight);
1003
1004 boolean colorHasAlpha = (color.getAlpha() != 255);
1005 boolean imageHasAlpha = (src.getTransparency() != BufferedImage.OPAQUE);
1006
1007 BufferedImage result;
1008
1009 /*
1010 * We need to make sure our resulting image that we render into contains
1011 * alpha if either our original image OR the padding color we are using
1012 * contain it.
1013 */
1014 if (colorHasAlpha || imageHasAlpha) {
1015 if (DEBUG)
1016 log(1,
1017 "Transparency FOUND in source image or color, using ARGB image type...");
1018
1019 result = new BufferedImage(newWidth, newHeight,
1020 BufferedImage.TYPE_INT_ARGB);
1021 } else {
1022 if (DEBUG)
1023 log(1,
1024 "Transparency NOT FOUND in source image or color, using RGB image type...");
1025
1026 result = new BufferedImage(newWidth, newHeight,
1027 BufferedImage.TYPE_INT_RGB);
1028 }
1029
1030 Graphics g = result.getGraphics();
1031
1032 // "Clear" the background of the new image with our padding color first.
1033 g.setColor(color);
1034 g.fillRect(0, 0, newWidth, newHeight);
1035
1036 // Draw the image into the center of the new padded image.
1037 g.drawImage(src, padding, padding, null);
1038 g.dispose();
1039
1040 if (DEBUG)
1041 log(0, "Padding Applied in %d ms", System.currentTimeMillis() - t);
1042
1043 // Apply any optional operations (if specified).
1044 if (ops != null && ops.length > 0)
1045 result = apply(result, ops);
1046
1047 return result;
1048 }
1049
1050 /**
1051 * Resize a given image (maintaining its original proportion) to a width and
1052 * height no bigger than <code>targetSize</code> and apply the given
1053 * {@link BufferedImageOp}s (if any) to the result before returning it.
1054 * <p/>
1055 * A scaling method of {@link Method#AUTOMATIC} and mode of
1056 * {@link Mode#AUTOMATIC} are used.
1057 * <p/>
1058 * <strong>TIP</strong>: This operation leaves the original <code>src</code>
1059 * image unmodified. If the caller is done with the <code>src</code> image
1060 * after getting the result of this operation, remember to call
1061 * {@link BufferedImage#flush()} on the <code>src</code> to free up native
1062 * resources and make it easier for the GC to collect the unused image.
1063 *
1064 * @param src
1065 * The image that will be scaled.
1066 * @param targetSize
1067 * The target width and height (square) that you wish the image
1068 * to fit within.
1069 * @param ops
1070 * <code>0</code> or more optional image operations (e.g.
1071 * sharpen, blur, etc.) that can be applied to the final result
1072 * before returning the image.
1073 *
1074 * @return a new {@link BufferedImage} representing the scaled
1075 * <code>src</code> image.
1076 *
1077 * @throws IllegalArgumentException
1078 * if <code>src</code> is <code>null</code>.
1079 * @throws IllegalArgumentException
1080 * if <code>targetSize</code> is &lt; 0.
1081 * @throws ImagingOpException
1082 * if one of the given {@link BufferedImageOp}s fails to apply.
1083 * These exceptions bubble up from the inside of most of the
1084 * {@link BufferedImageOp} implementations and are explicitly
1085 * defined on the imgscalr API to make it easier for callers to
1086 * catch the exception (if they are passing along optional ops
1087 * to be applied). imgscalr takes detailed steps to avoid the
1088 * most common pitfalls that will cause {@link BufferedImageOp}s
1089 * to fail, even when using straight forward JDK-image
1090 * operations.
1091 */
1092 public static BufferedImage resize(BufferedImage src, int targetSize,
1093 BufferedImageOp... ops) throws IllegalArgumentException,
1094 ImagingOpException {
1095 return resize(src, Method.AUTOMATIC, Mode.AUTOMATIC, targetSize,
1096 targetSize, ops);
1097 }
1098
1099 /**
1100 * Resize a given image (maintaining its original proportion) to a width and
1101 * height no bigger than <code>targetSize</code> using the given scaling
1102 * method and apply the given {@link BufferedImageOp}s (if any) to the
1103 * result before returning it.
1104 * <p/>
1105 * A mode of {@link Mode#AUTOMATIC} is used.
1106 * <p/>
1107 * <strong>TIP</strong>: This operation leaves the original <code>src</code>
1108 * image unmodified. If the caller is done with the <code>src</code> image
1109 * after getting the result of this operation, remember to call
1110 * {@link BufferedImage#flush()} on the <code>src</code> to free up native
1111 * resources and make it easier for the GC to collect the unused image.
1112 *
1113 * @param src
1114 * The image that will be scaled.
1115 * @param scalingMethod
1116 * The method used for scaling the image; preferring speed to
1117 * quality or a balance of both.
1118 * @param targetSize
1119 * The target width and height (square) that you wish the image
1120 * to fit within.
1121 * @param ops
1122 * <code>0</code> or more optional image operations (e.g.
1123 * sharpen, blur, etc.) that can be applied to the final result
1124 * before returning the image.
1125 *
1126 * @return a new {@link BufferedImage} representing the scaled
1127 * <code>src</code> image.
1128 *
1129 * @throws IllegalArgumentException
1130 * if <code>src</code> is <code>null</code>.
1131 * @throws IllegalArgumentException
1132 * if <code>scalingMethod</code> is <code>null</code>.
1133 * @throws IllegalArgumentException
1134 * if <code>targetSize</code> is &lt; 0.
1135 * @throws ImagingOpException
1136 * if one of the given {@link BufferedImageOp}s fails to apply.
1137 * These exceptions bubble up from the inside of most of the
1138 * {@link BufferedImageOp} implementations and are explicitly
1139 * defined on the imgscalr API to make it easier for callers to
1140 * catch the exception (if they are passing along optional ops
1141 * to be applied). imgscalr takes detailed steps to avoid the
1142 * most common pitfalls that will cause {@link BufferedImageOp}s
1143 * to fail, even when using straight forward JDK-image
1144 * operations.
1145 *
1146 * @see Method
1147 */
1148 public static BufferedImage resize(BufferedImage src, Method scalingMethod,
1149 int targetSize, BufferedImageOp... ops)
1150 throws IllegalArgumentException, ImagingOpException {
1151 return resize(src, scalingMethod, Mode.AUTOMATIC, targetSize,
1152 targetSize, ops);
1153 }
1154
1155 /**
1156 * Resize a given image (maintaining its original proportion) to a width and
1157 * height no bigger than <code>targetSize</code> (or fitting the image to
1158 * the given WIDTH or HEIGHT explicitly, depending on the {@link Mode}
1159 * specified) and apply the given {@link BufferedImageOp}s (if any) to the
1160 * result before returning it.
1161 * <p/>
1162 * A scaling method of {@link Method#AUTOMATIC} is used.
1163 * <p/>
1164 * <strong>TIP</strong>: This operation leaves the original <code>src</code>
1165 * image unmodified. If the caller is done with the <code>src</code> image
1166 * after getting the result of this operation, remember to call
1167 * {@link BufferedImage#flush()} on the <code>src</code> to free up native
1168 * resources and make it easier for the GC to collect the unused image.
1169 *
1170 * @param src
1171 * The image that will be scaled.
1172 * @param resizeMode
1173 * Used to indicate how imgscalr should calculate the final
1174 * target size for the image, either fitting the image to the
1175 * given width ({@link Mode#FIT_TO_WIDTH}) or fitting the image
1176 * to the given height ({@link Mode#FIT_TO_HEIGHT}). If
1177 * {@link Mode#AUTOMATIC} is passed in, imgscalr will calculate
1178 * proportional dimensions for the scaled image based on its
1179 * orientation (landscape, square or portrait). Unless you have
1180 * very specific size requirements, most of the time you just
1181 * want to use {@link Mode#AUTOMATIC} to "do the right thing".
1182 * @param targetSize
1183 * The target width and height (square) that you wish the image
1184 * to fit within.
1185 * @param ops
1186 * <code>0</code> or more optional image operations (e.g.
1187 * sharpen, blur, etc.) that can be applied to the final result
1188 * before returning the image.
1189 *
1190 * @return a new {@link BufferedImage} representing the scaled
1191 * <code>src</code> image.
1192 *
1193 * @throws IllegalArgumentException
1194 * if <code>src</code> is <code>null</code>.
1195 * @throws IllegalArgumentException
1196 * if <code>resizeMode</code> is <code>null</code>.
1197 * @throws IllegalArgumentException
1198 * if <code>targetSize</code> is &lt; 0.
1199 * @throws ImagingOpException
1200 * if one of the given {@link BufferedImageOp}s fails to apply.
1201 * These exceptions bubble up from the inside of most of the
1202 * {@link BufferedImageOp} implementations and are explicitly
1203 * defined on the imgscalr API to make it easier for callers to
1204 * catch the exception (if they are passing along optional ops
1205 * to be applied). imgscalr takes detailed steps to avoid the
1206 * most common pitfalls that will cause {@link BufferedImageOp}s
1207 * to fail, even when using straight forward JDK-image
1208 * operations.
1209 *
1210 * @see Mode
1211 */
1212 public static BufferedImage resize(BufferedImage src, Mode resizeMode,
1213 int targetSize, BufferedImageOp... ops)
1214 throws IllegalArgumentException, ImagingOpException {
1215 return resize(src, Method.AUTOMATIC, resizeMode, targetSize,
1216 targetSize, ops);
1217 }
1218
1219 /**
1220 * Resize a given image (maintaining its original proportion) to a width and
1221 * height no bigger than <code>targetSize</code> (or fitting the image to
1222 * the given WIDTH or HEIGHT explicitly, depending on the {@link Mode}
1223 * specified) using the given scaling method and apply the given
1224 * {@link BufferedImageOp}s (if any) to the result before returning it.
1225 * <p/>
1226 * <strong>TIP</strong>: This operation leaves the original <code>src</code>
1227 * image unmodified. If the caller is done with the <code>src</code> image
1228 * after getting the result of this operation, remember to call
1229 * {@link BufferedImage#flush()} on the <code>src</code> to free up native
1230 * resources and make it easier for the GC to collect the unused image.
1231 *
1232 * @param src
1233 * The image that will be scaled.
1234 * @param scalingMethod
1235 * The method used for scaling the image; preferring speed to
1236 * quality or a balance of both.
1237 * @param resizeMode
1238 * Used to indicate how imgscalr should calculate the final
1239 * target size for the image, either fitting the image to the
1240 * given width ({@link Mode#FIT_TO_WIDTH}) or fitting the image
1241 * to the given height ({@link Mode#FIT_TO_HEIGHT}). If
1242 * {@link Mode#AUTOMATIC} is passed in, imgscalr will calculate
1243 * proportional dimensions for the scaled image based on its
1244 * orientation (landscape, square or portrait). Unless you have
1245 * very specific size requirements, most of the time you just
1246 * want to use {@link Mode#AUTOMATIC} to "do the right thing".
1247 * @param targetSize
1248 * The target width and height (square) that you wish the image
1249 * to fit within.
1250 * @param ops
1251 * <code>0</code> or more optional image operations (e.g.
1252 * sharpen, blur, etc.) that can be applied to the final result
1253 * before returning the image.
1254 *
1255 * @return a new {@link BufferedImage} representing the scaled
1256 * <code>src</code> image.
1257 *
1258 * @throws IllegalArgumentException
1259 * if <code>src</code> is <code>null</code>.
1260 * @throws IllegalArgumentException
1261 * if <code>scalingMethod</code> is <code>null</code>.
1262 * @throws IllegalArgumentException
1263 * if <code>resizeMode</code> is <code>null</code>.
1264 * @throws IllegalArgumentException
1265 * if <code>targetSize</code> is &lt; 0.
1266 * @throws ImagingOpException
1267 * if one of the given {@link BufferedImageOp}s fails to apply.
1268 * These exceptions bubble up from the inside of most of the
1269 * {@link BufferedImageOp} implementations and are explicitly
1270 * defined on the imgscalr API to make it easier for callers to
1271 * catch the exception (if they are passing along optional ops
1272 * to be applied). imgscalr takes detailed steps to avoid the
1273 * most common pitfalls that will cause {@link BufferedImageOp}s
1274 * to fail, even when using straight forward JDK-image
1275 * operations.
1276 *
1277 * @see Method
1278 * @see Mode
1279 */
1280 public static BufferedImage resize(BufferedImage src, Method scalingMethod,
1281 Mode resizeMode, int targetSize, BufferedImageOp... ops)
1282 throws IllegalArgumentException, ImagingOpException {
1283 return resize(src, scalingMethod, resizeMode, targetSize, targetSize,
1284 ops);
1285 }
1286
1287 /**
1288 * Resize a given image (maintaining its original proportion) to the target
1289 * width and height and apply the given {@link BufferedImageOp}s (if any) to
1290 * the result before returning it.
1291 * <p/>
1292 * A scaling method of {@link Method#AUTOMATIC} and mode of
1293 * {@link Mode#AUTOMATIC} are used.
1294 * <p/>
1295 * <strong>TIP</strong>: See the class description to understand how this
1296 * class handles recalculation of the <code>targetWidth</code> or
1297 * <code>targetHeight</code> depending on the image's orientation in order
1298 * to maintain the original proportion.
1299 * <p/>
1300 * <strong>TIP</strong>: This operation leaves the original <code>src</code>
1301 * image unmodified. If the caller is done with the <code>src</code> image
1302 * after getting the result of this operation, remember to call
1303 * {@link BufferedImage#flush()} on the <code>src</code> to free up native
1304 * resources and make it easier for the GC to collect the unused image.
1305 *
1306 * @param src
1307 * The image that will be scaled.
1308 * @param targetWidth
1309 * The target width that you wish the image to have.
1310 * @param targetHeight
1311 * The target height that you wish the image to have.
1312 * @param ops
1313 * <code>0</code> or more optional image operations (e.g.
1314 * sharpen, blur, etc.) that can be applied to the final result
1315 * before returning the image.
1316 *
1317 * @return a new {@link BufferedImage} representing the scaled
1318 * <code>src</code> image.
1319 *
1320 * @throws IllegalArgumentException
1321 * if <code>src</code> is <code>null</code>.
1322 * @throws IllegalArgumentException
1323 * if <code>targetWidth</code> is &lt; 0 or if
1324 * <code>targetHeight</code> is &lt; 0.
1325 * @throws ImagingOpException
1326 * if one of the given {@link BufferedImageOp}s fails to apply.
1327 * These exceptions bubble up from the inside of most of the
1328 * {@link BufferedImageOp} implementations and are explicitly
1329 * defined on the imgscalr API to make it easier for callers to
1330 * catch the exception (if they are passing along optional ops
1331 * to be applied). imgscalr takes detailed steps to avoid the
1332 * most common pitfalls that will cause {@link BufferedImageOp}s
1333 * to fail, even when using straight forward JDK-image
1334 * operations.
1335 */
1336 public static BufferedImage resize(BufferedImage src, int targetWidth,
1337 int targetHeight, BufferedImageOp... ops)
1338 throws IllegalArgumentException, ImagingOpException {
1339 return resize(src, Method.AUTOMATIC, Mode.AUTOMATIC, targetWidth,
1340 targetHeight, ops);
1341 }
1342
1343 /**
1344 * Resize a given image (maintaining its original proportion) to the target
1345 * width and height using the given scaling method and apply the given
1346 * {@link BufferedImageOp}s (if any) to the result before returning it.
1347 * <p/>
1348 * A mode of {@link Mode#AUTOMATIC} is used.
1349 * <p/>
1350 * <strong>TIP</strong>: See the class description to understand how this
1351 * class handles recalculation of the <code>targetWidth</code> or
1352 * <code>targetHeight</code> depending on the image's orientation in order
1353 * to maintain the original proportion.
1354 * <p/>
1355 * <strong>TIP</strong>: This operation leaves the original <code>src</code>
1356 * image unmodified. If the caller is done with the <code>src</code> image
1357 * after getting the result of this operation, remember to call
1358 * {@link BufferedImage#flush()} on the <code>src</code> to free up native
1359 * resources and make it easier for the GC to collect the unused image.
1360 *
1361 * @param src
1362 * The image that will be scaled.
1363 * @param scalingMethod
1364 * The method used for scaling the image; preferring speed to
1365 * quality or a balance of both.
1366 * @param targetWidth
1367 * The target width that you wish the image to have.
1368 * @param targetHeight
1369 * The target height that you wish the image to have.
1370 * @param ops
1371 * <code>0</code> or more optional image operations (e.g.
1372 * sharpen, blur, etc.) that can be applied to the final result
1373 * before returning the image.
1374 *
1375 * @return a new {@link BufferedImage} representing the scaled
1376 * <code>src</code> image.
1377 *
1378 * @throws IllegalArgumentException
1379 * if <code>src</code> is <code>null</code>.
1380 * @throws IllegalArgumentException
1381 * if <code>scalingMethod</code> is <code>null</code>.
1382 * @throws IllegalArgumentException
1383 * if <code>targetWidth</code> is &lt; 0 or if
1384 * <code>targetHeight</code> is &lt; 0.
1385 * @throws ImagingOpException
1386 * if one of the given {@link BufferedImageOp}s fails to apply.
1387 * These exceptions bubble up from the inside of most of the
1388 * {@link BufferedImageOp} implementations and are explicitly
1389 * defined on the imgscalr API to make it easier for callers to
1390 * catch the exception (if they are passing along optional ops
1391 * to be applied). imgscalr takes detailed steps to avoid the
1392 * most common pitfalls that will cause {@link BufferedImageOp}s
1393 * to fail, even when using straight forward JDK-image
1394 * operations.
1395 *
1396 * @see Method
1397 */
1398 public static BufferedImage resize(BufferedImage src, Method scalingMethod,
1399 int targetWidth, int targetHeight, BufferedImageOp... ops) {
1400 return resize(src, scalingMethod, Mode.AUTOMATIC, targetWidth,
1401 targetHeight, ops);
1402 }
1403
1404 /**
1405 * Resize a given image (maintaining its original proportion) to the target
1406 * width and height (or fitting the image to the given WIDTH or HEIGHT
1407 * explicitly, depending on the {@link Mode} specified) and apply the given
1408 * {@link BufferedImageOp}s (if any) to the result before returning it.
1409 * <p/>
1410 * A scaling method of {@link Method#AUTOMATIC} is used.
1411 * <p/>
1412 * <strong>TIP</strong>: See the class description to understand how this
1413 * class handles recalculation of the <code>targetWidth</code> or
1414 * <code>targetHeight</code> depending on the image's orientation in order
1415 * to maintain the original proportion.
1416 * <p/>
1417 * <strong>TIP</strong>: This operation leaves the original <code>src</code>
1418 * image unmodified. If the caller is done with the <code>src</code> image
1419 * after getting the result of this operation, remember to call
1420 * {@link BufferedImage#flush()} on the <code>src</code> to free up native
1421 * resources and make it easier for the GC to collect the unused image.
1422 *
1423 * @param src
1424 * The image that will be scaled.
1425 * @param resizeMode
1426 * Used to indicate how imgscalr should calculate the final
1427 * target size for the image, either fitting the image to the
1428 * given width ({@link Mode#FIT_TO_WIDTH}) or fitting the image
1429 * to the given height ({@link Mode#FIT_TO_HEIGHT}). If
1430 * {@link Mode#AUTOMATIC} is passed in, imgscalr will calculate
1431 * proportional dimensions for the scaled image based on its
1432 * orientation (landscape, square or portrait). Unless you have
1433 * very specific size requirements, most of the time you just
1434 * want to use {@link Mode#AUTOMATIC} to "do the right thing".
1435 * @param targetWidth
1436 * The target width that you wish the image to have.
1437 * @param targetHeight
1438 * The target height that you wish the image to have.
1439 * @param ops
1440 * <code>0</code> or more optional image operations (e.g.
1441 * sharpen, blur, etc.) that can be applied to the final result
1442 * before returning the image.
1443 *
1444 * @return a new {@link BufferedImage} representing the scaled
1445 * <code>src</code> image.
1446 *
1447 * @throws IllegalArgumentException
1448 * if <code>src</code> is <code>null</code>.
1449 * @throws IllegalArgumentException
1450 * if <code>resizeMode</code> is <code>null</code>.
1451 * @throws IllegalArgumentException
1452 * if <code>targetWidth</code> is &lt; 0 or if
1453 * <code>targetHeight</code> is &lt; 0.
1454 * @throws ImagingOpException
1455 * if one of the given {@link BufferedImageOp}s fails to apply.
1456 * These exceptions bubble up from the inside of most of the
1457 * {@link BufferedImageOp} implementations and are explicitly
1458 * defined on the imgscalr API to make it easier for callers to
1459 * catch the exception (if they are passing along optional ops
1460 * to be applied). imgscalr takes detailed steps to avoid the
1461 * most common pitfalls that will cause {@link BufferedImageOp}s
1462 * to fail, even when using straight forward JDK-image
1463 * operations.
1464 *
1465 * @see Mode
1466 */
1467 public static BufferedImage resize(BufferedImage src, Mode resizeMode,
1468 int targetWidth, int targetHeight, BufferedImageOp... ops)
1469 throws IllegalArgumentException, ImagingOpException {
1470 return resize(src, Method.AUTOMATIC, resizeMode, targetWidth,
1471 targetHeight, ops);
1472 }
1473
1474 /**
1475 * Resize a given image (maintaining its original proportion) to the target
1476 * width and height (or fitting the image to the given WIDTH or HEIGHT
1477 * explicitly, depending on the {@link Mode} specified) using the given
1478 * scaling method and apply the given {@link BufferedImageOp}s (if any) to
1479 * the result before returning it.
1480 * <p/>
1481 * <strong>TIP</strong>: See the class description to understand how this
1482 * class handles recalculation of the <code>targetWidth</code> or
1483 * <code>targetHeight</code> depending on the image's orientation in order
1484 * to maintain the original proportion.
1485 * <p/>
1486 * <strong>TIP</strong>: This operation leaves the original <code>src</code>
1487 * image unmodified. If the caller is done with the <code>src</code> image
1488 * after getting the result of this operation, remember to call
1489 * {@link BufferedImage#flush()} on the <code>src</code> to free up native
1490 * resources and make it easier for the GC to collect the unused image.
1491 *
1492 * @param src
1493 * The image that will be scaled.
1494 * @param scalingMethod
1495 * The method used for scaling the image; preferring speed to
1496 * quality or a balance of both.
1497 * @param resizeMode
1498 * Used to indicate how imgscalr should calculate the final
1499 * target size for the image, either fitting the image to the
1500 * given width ({@link Mode#FIT_TO_WIDTH}) or fitting the image
1501 * to the given height ({@link Mode#FIT_TO_HEIGHT}). If
1502 * {@link Mode#AUTOMATIC} is passed in, imgscalr will calculate
1503 * proportional dimensions for the scaled image based on its
1504 * orientation (landscape, square or portrait). Unless you have
1505 * very specific size requirements, most of the time you just
1506 * want to use {@link Mode#AUTOMATIC} to "do the right thing".
1507 * @param targetWidth
1508 * The target width that you wish the image to have.
1509 * @param targetHeight
1510 * The target height that you wish the image to have.
1511 * @param ops
1512 * <code>0</code> or more optional image operations (e.g.
1513 * sharpen, blur, etc.) that can be applied to the final result
1514 * before returning the image.
1515 *
1516 * @return a new {@link BufferedImage} representing the scaled
1517 * <code>src</code> image.
1518 *
1519 * @throws IllegalArgumentException
1520 * if <code>src</code> is <code>null</code>.
1521 * @throws IllegalArgumentException
1522 * if <code>scalingMethod</code> is <code>null</code>.
1523 * @throws IllegalArgumentException
1524 * if <code>resizeMode</code> is <code>null</code>.
1525 * @throws IllegalArgumentException
1526 * if <code>targetWidth</code> is &lt; 0 or if
1527 * <code>targetHeight</code> is &lt; 0.
1528 * @throws ImagingOpException
1529 * if one of the given {@link BufferedImageOp}s fails to apply.
1530 * These exceptions bubble up from the inside of most of the
1531 * {@link BufferedImageOp} implementations and are explicitly
1532 * defined on the imgscalr API to make it easier for callers to
1533 * catch the exception (if they are passing along optional ops
1534 * to be applied). imgscalr takes detailed steps to avoid the
1535 * most common pitfalls that will cause {@link BufferedImageOp}s
1536 * to fail, even when using straight forward JDK-image
1537 * operations.
1538 *
1539 * @see Method
1540 * @see Mode
1541 */
1542 public static BufferedImage resize(BufferedImage src, Method scalingMethod,
1543 Mode resizeMode, int targetWidth, int targetHeight,
1544 BufferedImageOp... ops) throws IllegalArgumentException,
1545 ImagingOpException {
1546 long t = System.currentTimeMillis();
1547
1548 if (src == null)
1549 throw new IllegalArgumentException("src cannot be null");
1550 if (targetWidth < 0)
1551 throw new IllegalArgumentException("targetWidth must be >= 0");
1552 if (targetHeight < 0)
1553 throw new IllegalArgumentException("targetHeight must be >= 0");
1554 if (scalingMethod == null)
1555 throw new IllegalArgumentException(
1556 "scalingMethod cannot be null. A good default value is Method.AUTOMATIC.");
1557 if (resizeMode == null)
1558 throw new IllegalArgumentException(
1559 "resizeMode cannot be null. A good default value is Mode.AUTOMATIC.");
1560
1561 BufferedImage result = null;
1562
1563 int currentWidth = src.getWidth();
1564 int currentHeight = src.getHeight();
1565
1566 // <= 1 is a square or landscape-oriented image, > 1 is a portrait.
1567 float ratio = ((float) currentHeight / (float) currentWidth);
1568
1569 if (DEBUG)
1570 log(0,
1571 "Resizing Image [size=%dx%d, resizeMode=%s, orientation=%s, ratio(H/W)=%f] to [targetSize=%dx%d]",
1572 currentWidth, currentHeight, resizeMode,
1573 (ratio <= 1 ? "Landscape/Square" : "Portrait"), ratio,
1574 targetWidth, targetHeight);
1575
1576 /*
1577 * First determine if ANY size calculation needs to be done, in the case
1578 * of FIT_EXACT, ignore image proportions and orientation and just use
1579 * what the user sent in, otherwise the proportion of the picture must
1580 * be honored.
1581 *
1582 * The way that is done is to figure out if the image is in a
1583 * LANDSCAPE/SQUARE or PORTRAIT orientation and depending on its
1584 * orientation, use the primary dimension (width for LANDSCAPE/SQUARE
1585 * and height for PORTRAIT) to recalculate the alternative (height and
1586 * width respectively) value that adheres to the existing ratio.
1587 *
1588 * This helps make life easier for the caller as they don't need to
1589 * pre-compute proportional dimensions before calling the API, they can
1590 * just specify the dimensions they would like the image to roughly fit
1591 * within and it will do the right thing without mangling the result.
1592 */
1593 if (resizeMode != Mode.FIT_EXACT) {
1594 if ((ratio <= 1 && resizeMode == Mode.AUTOMATIC)
1595 || (resizeMode == Mode.FIT_TO_WIDTH)) {
1596 // First make sure we need to do any work in the first place
1597 if (targetWidth == src.getWidth())
1598 return src;
1599
1600 // Save for detailed logging (this is cheap).
1601 int originalTargetHeight = targetHeight;
1602
1603 /*
1604 * Landscape or Square Orientation: Ignore the given height and
1605 * re-calculate a proportionally correct value based on the
1606 * targetWidth.
1607 */
1608 targetHeight = Math.round((float) targetWidth * ratio);
1609
1610 if (DEBUG && originalTargetHeight != targetHeight)
1611 log(1,
1612 "Auto-Corrected targetHeight [from=%d to=%d] to honor image proportions.",
1613 originalTargetHeight, targetHeight);
1614 } else {
1615 // First make sure we need to do any work in the first place
1616 if (targetHeight == src.getHeight())
1617 return src;
1618
1619 // Save for detailed logging (this is cheap).
1620 int originalTargetWidth = targetWidth;
1621
1622 /*
1623 * Portrait Orientation: Ignore the given width and re-calculate
1624 * a proportionally correct value based on the targetHeight.
1625 */
1626 targetWidth = Math.round((float) targetHeight / ratio);
1627
1628 if (DEBUG && originalTargetWidth != targetWidth)
1629 log(1,
1630 "Auto-Corrected targetWidth [from=%d to=%d] to honor image proportions.",
1631 originalTargetWidth, targetWidth);
1632 }
1633 } else {
1634 if (DEBUG)
1635 log(1,
1636 "Resize Mode FIT_EXACT used, no width/height checking or re-calculation will be done.");
1637 }
1638
1639 // If AUTOMATIC was specified, determine the real scaling method.
1640 if (scalingMethod == Scalr.Method.AUTOMATIC)
1641 scalingMethod = determineScalingMethod(targetWidth, targetHeight,
1642 ratio);
1643
1644 if (DEBUG)
1645 log(1, "Using Scaling Method: %s", scalingMethod);
1646
1647 // Now we scale the image
1648 if (scalingMethod == Scalr.Method.SPEED) {
1649 result = scaleImage(src, targetWidth, targetHeight,
1650 RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);
1651 } else if (scalingMethod == Scalr.Method.BALANCED) {
1652 result = scaleImage(src, targetWidth, targetHeight,
1653 RenderingHints.VALUE_INTERPOLATION_BILINEAR);
1654 } else if (scalingMethod == Scalr.Method.QUALITY
1655 || scalingMethod == Scalr.Method.ULTRA_QUALITY) {
1656 /*
1657 * If we are scaling up (in either width or height - since we know
1658 * the image will stay proportional we just check if either are
1659 * being scaled up), directly using a single BICUBIC will give us
1660 * better results then using Chris Campbell's incremental scaling
1661 * operation (and take a lot less time).
1662 *
1663 * If we are scaling down, we must use the incremental scaling
1664 * algorithm for the best result.
1665 */
1666 if (targetWidth > currentWidth || targetHeight > currentHeight) {
1667 if (DEBUG)
1668 log(1,
1669 "QUALITY scale-up, a single BICUBIC scale operation will be used...");
1670
1671 /*
1672 * BILINEAR and BICUBIC look similar the smaller the scale jump
1673 * upwards is, if the scale is larger BICUBIC looks sharper and
1674 * less fuzzy. But most importantly we have to use BICUBIC to
1675 * match the contract of the QUALITY rendering scalingMethod.
1676 * This note is just here for anyone reading the code and
1677 * wondering how they can speed their own calls up.
1678 */
1679 result = scaleImage(src, targetWidth, targetHeight,
1680 RenderingHints.VALUE_INTERPOLATION_BICUBIC);
1681 } else {
1682 if (DEBUG)
1683 log(1,
1684 "QUALITY scale-down, incremental scaling will be used...");
1685
1686 /*
1687 * Originally we wanted to use BILINEAR interpolation here
1688 * because it takes 1/3rd the time that the BICUBIC
1689 * interpolation does, however, when scaling large images down
1690 * to most sizes bigger than a thumbnail we witnessed noticeable
1691 * "softening" in the resultant image with BILINEAR that would
1692 * be unexpectedly annoying to a user expecting a "QUALITY"
1693 * scale of their original image. Instead BICUBIC was chosen to
1694 * honor the contract of a QUALITY scale of the original image.
1695 */
1696 result = scaleImageIncrementally(src, targetWidth,
1697 targetHeight, scalingMethod,
1698 RenderingHints.VALUE_INTERPOLATION_BICUBIC);
1699 }
1700 }
1701
1702 if (DEBUG)
1703 log(0, "Resized Image in %d ms", System.currentTimeMillis() - t);
1704
1705 // Apply any optional operations (if specified).
1706 if (ops != null && ops.length > 0)
1707 result = apply(result, ops);
1708
1709 return result;
1710 }
1711
1712 /**
1713 * Used to apply a {@link Rotation} and then <code>0</code> or more
1714 * {@link BufferedImageOp}s to a given image and return the result.
1715 * <p/>
1716 * <strong>TIP</strong>: This operation leaves the original <code>src</code>
1717 * image unmodified. If the caller is done with the <code>src</code> image
1718 * after getting the result of this operation, remember to call
1719 * {@link BufferedImage#flush()} on the <code>src</code> to free up native
1720 * resources and make it easier for the GC to collect the unused image.
1721 *
1722 * @param src
1723 * The image that will have the rotation applied to it.
1724 * @param rotation
1725 * The rotation that will be applied to the image.
1726 * @param ops
1727 * Zero or more optional image operations (e.g. sharpen, blur,
1728 * etc.) that can be applied to the final result before returning
1729 * the image.
1730 *
1731 * @return a new {@link BufferedImage} representing <code>src</code> rotated
1732 * by the given amount and any optional ops applied to it.
1733 *
1734 * @throws IllegalArgumentException
1735 * if <code>src</code> is <code>null</code>.
1736 * @throws IllegalArgumentException
1737 * if <code>rotation</code> is <code>null</code>.
1738 * @throws ImagingOpException
1739 * if one of the given {@link BufferedImageOp}s fails to apply.
1740 * These exceptions bubble up from the inside of most of the
1741 * {@link BufferedImageOp} implementations and are explicitly
1742 * defined on the imgscalr API to make it easier for callers to
1743 * catch the exception (if they are passing along optional ops
1744 * to be applied). imgscalr takes detailed steps to avoid the
1745 * most common pitfalls that will cause {@link BufferedImageOp}s
1746 * to fail, even when using straight forward JDK-image
1747 * operations.
1748 *
1749 * @see Rotation
1750 */
1751 public static BufferedImage rotate(BufferedImage src, Rotation rotation,
1752 BufferedImageOp... ops) throws IllegalArgumentException,
1753 ImagingOpException {
1754 long t = System.currentTimeMillis();
1755
1756 if (src == null)
1757 throw new IllegalArgumentException("src cannot be null");
1758 if (rotation == null)
1759 throw new IllegalArgumentException("rotation cannot be null");
1760
1761 if (DEBUG)
1762 log(0, "Rotating Image [%s]...", rotation);
1763
1764 /*
1765 * Setup the default width/height values from our image.
1766 *
1767 * In the case of a 90 or 270 (-90) degree rotation, these two values
1768 * flip-flop and we will correct those cases down below in the switch
1769 * statement.
1770 */
1771 int newWidth = src.getWidth();
1772 int newHeight = src.getHeight();
1773
1774 /*
1775 * We create a transform per operation request as (oddly enough) it ends
1776 * up being faster for the VM to create, use and destroy these instances
1777 * than it is to re-use a single AffineTransform per-thread via the
1778 * AffineTransform.setTo(...) methods which was my first choice (less
1779 * object creation); after benchmarking this explicit case and looking
1780 * at just how much code gets run inside of setTo() I opted for a new AT
1781 * for every rotation.
1782 *
1783 * Besides the performance win, trying to safely reuse AffineTransforms
1784 * via setTo(...) would have required ThreadLocal instances to avoid
1785 * race conditions where two or more resize threads are manipulating the
1786 * same transform before applying it.
1787 *
1788 * Misusing ThreadLocals are one of the #1 reasons for memory leaks in
1789 * server applications and since we have no nice way to hook into the
1790 * init/destroy Servlet cycle or any other initialization cycle for this
1791 * library to automatically call ThreadLocal.remove() to avoid the
1792 * memory leak, it would have made using this library *safely* on the
1793 * server side much harder.
1794 *
1795 * So we opt for creating individual transforms per rotation op and let
1796 * the VM clean them up in a GC. I only clarify all this reasoning here
1797 * for anyone else reading this code and being tempted to reuse the AT
1798 * instances of performance gains; there aren't any AND you get a lot of
1799 * pain along with it.
1800 */
1801 AffineTransform tx = new AffineTransform();
1802
1803 switch (rotation) {
1804 case CW_90:
1805 /*
1806 * A 90 or -90 degree rotation will cause the height and width to
1807 * flip-flop from the original image to the rotated one.
1808 */
1809 newWidth = src.getHeight();
1810 newHeight = src.getWidth();
1811
1812 // Reminder: newWidth == result.getHeight() at this point
1813 tx.translate(newWidth, 0);
1814 tx.rotate(Math.toRadians(90));
1815
1816 break;
1817
1818 case CW_270:
1819 /*
1820 * A 90 or -90 degree rotation will cause the height and width to
1821 * flip-flop from the original image to the rotated one.
1822 */
1823 newWidth = src.getHeight();
1824 newHeight = src.getWidth();
1825
1826 // Reminder: newHeight == result.getWidth() at this point
1827 tx.translate(0, newHeight);
1828 tx.rotate(Math.toRadians(-90));
1829 break;
1830
1831 case CW_180:
1832 tx.translate(newWidth, newHeight);
1833 tx.rotate(Math.toRadians(180));
1834 break;
1835
1836 case FLIP_HORZ:
1837 tx.translate(newWidth, 0);
1838 tx.scale(-1.0, 1.0);
1839 break;
1840
1841 case FLIP_VERT:
1842 tx.translate(0, newHeight);
1843 tx.scale(1.0, -1.0);
1844 break;
1845 }
1846
1847 // Create our target image we will render the rotated result to.
1848 BufferedImage result = createOptimalImage(src, newWidth, newHeight);
1849 Graphics2D g2d = (Graphics2D) result.createGraphics();
1850
1851 /*
1852 * Render the resultant image to our new rotatedImage buffer, applying
1853 * the AffineTransform that we calculated above during rendering so the
1854 * pixels from the old position are transposed to the new positions in
1855 * the resulting image correctly.
1856 */
1857 g2d.drawImage(src, tx, null);
1858 g2d.dispose();
1859
1860 if (DEBUG)
1861 log(0, "Rotation Applied in %d ms, result [width=%d, height=%d]",
1862 System.currentTimeMillis() - t, result.getWidth(),
1863 result.getHeight());
1864
1865 // Apply any optional operations (if specified).
1866 if (ops != null && ops.length > 0)
1867 result = apply(result, ops);
1868
1869 return result;
1870 }
1871
1872 /**
1873 * Used to write out a useful and well-formatted log message by any piece of
1874 * code inside of the imgscalr library.
1875 * <p/>
1876 * If a message cannot be logged (logging is disabled) then this method
1877 * returns immediately.
1878 * <p/>
1879 * <strong>NOTE</strong>: Because Java will auto-box primitive arguments
1880 * into Objects when building out the <code>params</code> array, care should
1881 * be taken not to call this method with primitive values unless
1882 * {@link Scalr#DEBUG} is <code>true</code>; otherwise the VM will be
1883 * spending time performing unnecessary auto-boxing calculations.
1884 *
1885 * @param depth
1886 * The indentation level of the log message.
1887 * @param message
1888 * The log message in <a href=
1889 * "http://download.oracle.com/javase/6/docs/api/java/util/Formatter.html#syntax"
1890 * >format string syntax</a> that will be logged.
1891 * @param params
1892 * The parameters that will be swapped into all the place holders
1893 * in the original messages before being logged.
1894 *
1895 * @see Scalr#LOG_PREFIX
1896 * @see Scalr#LOG_PREFIX_PROPERTY_NAME
1897 */
1898 protected static void log(int depth, String message, Object... params) {
1899 if (Scalr.DEBUG) {
1900 System.out.print(Scalr.LOG_PREFIX);
1901
1902 for (int i = 0; i < depth; i++)
1903 System.out.print("\t");
1904
1905 System.out.printf(message, params);
1906 System.out.println();
1907 }
1908 }
1909
1910 /**
1911 * Used to create a {@link BufferedImage} with the most optimal RGB TYPE (
1912 * {@link BufferedImage#TYPE_INT_RGB} or {@link BufferedImage#TYPE_INT_ARGB}
1913 * ) capable of being rendered into from the given <code>src</code>. The
1914 * width and height of both images will be identical.
1915 * <p/>
1916 * This does not perform a copy of the image data from <code>src</code> into
1917 * the result image; see {@link #copyToOptimalImage(BufferedImage)} for
1918 * that.
1919 * <p/>
1920 * We force all rendering results into one of these two types, avoiding the
1921 * case where a source image is of an unsupported (or poorly supported)
1922 * format by Java2D causing the rendering result to end up looking terrible
1923 * (common with GIFs) or be totally corrupt (e.g. solid black image).
1924 * <p/>
1925 * Originally reported by Magnus Kvalheim from Movellas when scaling certain
1926 * GIF and PNG images.
1927 *
1928 * @param src
1929 * The source image that will be analyzed to determine the most
1930 * optimal image type it can be rendered into.
1931 *
1932 * @return a new {@link BufferedImage} representing the most optimal target
1933 * image type that <code>src</code> can be rendered into.
1934 *
1935 * @see <a
1936 * href="http://www.mail-archive.com/[email protected]/msg05621.html">How
1937 * Java2D handles poorly supported image types</a>
1938 * @see <a
1939 * href="http://code.google.com/p/java-image-scaling/source/browse/trunk/src/main/java/com/mortennobel/imagescaling/MultiStepRescaleOp.java">Thanks
1940 * to Morten Nobel for implementation hint</a>
1941 */
1942 protected static BufferedImage createOptimalImage(BufferedImage src) {
1943 return createOptimalImage(src, src.getWidth(), src.getHeight());
1944 }
1945
1946 /**
1947 * Used to create a {@link BufferedImage} with the given dimensions and the
1948 * most optimal RGB TYPE ( {@link BufferedImage#TYPE_INT_RGB} or
1949 * {@link BufferedImage#TYPE_INT_ARGB} ) capable of being rendered into from
1950 * the given <code>src</code>.
1951 * <p/>
1952 * This does not perform a copy of the image data from <code>src</code> into
1953 * the result image; see {@link #copyToOptimalImage(BufferedImage)} for
1954 * that.
1955 * <p/>
1956 * We force all rendering results into one of these two types, avoiding the
1957 * case where a source image is of an unsupported (or poorly supported)
1958 * format by Java2D causing the rendering result to end up looking terrible
1959 * (common with GIFs) or be totally corrupt (e.g. solid black image).
1960 * <p/>
1961 * Originally reported by Magnus Kvalheim from Movellas when scaling certain
1962 * GIF and PNG images.
1963 *
1964 * @param src
1965 * The source image that will be analyzed to determine the most
1966 * optimal image type it can be rendered into.
1967 * @param width
1968 * The width of the newly created resulting image.
1969 * @param height
1970 * The height of the newly created resulting image.
1971 *
1972 * @return a new {@link BufferedImage} representing the most optimal target
1973 * image type that <code>src</code> can be rendered into.
1974 *
1975 * @throws IllegalArgumentException
1976 * if <code>width</code> or <code>height</code> are &lt; 0.
1977 *
1978 * @see <a
1979 * href="http://www.mail-archive.com/[email protected]/msg05621.html">How
1980 * Java2D handles poorly supported image types</a>
1981 * @see <a
1982 * href="http://code.google.com/p/java-image-scaling/source/browse/trunk/src/main/java/com/mortennobel/imagescaling/MultiStepRescaleOp.java">Thanks
1983 * to Morten Nobel for implementation hint</a>
1984 */
1985 protected static BufferedImage createOptimalImage(BufferedImage src,
1986 int width, int height) throws IllegalArgumentException {
1987 if (width < 0 || height < 0)
1988 throw new IllegalArgumentException("width [" + width
1989 + "] and height [" + height + "] must be >= 0");
1990
1991 return new BufferedImage(
1992 width,
1993 height,
1994 (src.getTransparency() == Transparency.OPAQUE ? BufferedImage.TYPE_INT_RGB
1995 : BufferedImage.TYPE_INT_ARGB));
1996 }
1997
1998 /**
1999 * Used to copy a {@link BufferedImage} from a non-optimal type into a new
2000 * {@link BufferedImage} instance of an optimal type (RGB or ARGB). If
2001 * <code>src</code> is already of an optimal type, then it is returned
2002 * unmodified.
2003 * <p/>
2004 * This method is meant to be used by any calling code (imgscalr's or
2005 * otherwise) to convert any inbound image from a poorly supported image
2006 * type into the 2 most well-supported image types in Java2D (
2007 * {@link BufferedImage#TYPE_INT_RGB} or {@link BufferedImage#TYPE_INT_ARGB}
2008 * ) in order to ensure all subsequent graphics operations are performed as
2009 * efficiently and correctly as possible.
2010 * <p/>
2011 * When using Java2D to work with image types that are not well supported,
2012 * the results can be anything from exceptions bubbling up from the depths
2013 * of Java2D to images being completely corrupted and just returned as solid
2014 * black.
2015 *
2016 * @param src
2017 * The image to copy (if necessary) into an optimally typed
2018 * {@link BufferedImage}.
2019 *
2020 * @return a representation of the <code>src</code> image in an optimally
2021 * typed {@link BufferedImage}, otherwise <code>src</code> if it was
2022 * already of an optimal type.
2023 *
2024 * @throws IllegalArgumentException
2025 * if <code>src</code> is <code>null</code>.
2026 */
2027 protected static BufferedImage copyToOptimalImage(BufferedImage src)
2028 throws IllegalArgumentException {
2029 if (src == null)
2030 throw new IllegalArgumentException("src cannot be null");
2031
2032 // Calculate the type depending on the presence of alpha.
2033 int type = (src.getTransparency() == Transparency.OPAQUE ? BufferedImage.TYPE_INT_RGB
2034 : BufferedImage.TYPE_INT_ARGB);
2035 BufferedImage result = new BufferedImage(src.getWidth(),
2036 src.getHeight(), type);
2037
2038 // Render the src image into our new optimal source.
2039 Graphics g = result.getGraphics();
2040 g.drawImage(src, 0, 0, null);
2041 g.dispose();
2042
2043 return result;
2044 }
2045
2046 /**
2047 * Used to determine the scaling {@link Method} that is best suited for
2048 * scaling the image to the targeted dimensions.
2049 * <p/>
2050 * This method is intended to be used to select a specific scaling
2051 * {@link Method} when a {@link Method#AUTOMATIC} method is specified. This
2052 * method utilizes the {@link Scalr#THRESHOLD_QUALITY_BALANCED} and
2053 * {@link Scalr#THRESHOLD_BALANCED_SPEED} thresholds when selecting which
2054 * method should be used by comparing the primary dimension (width or
2055 * height) against the threshold and seeing where the image falls. The
2056 * primary dimension is determined by looking at the orientation of the
2057 * image: landscape or square images use their width and portrait-oriented
2058 * images use their height.
2059 *
2060 * @param targetWidth
2061 * The target width for the scaled image.
2062 * @param targetHeight
2063 * The target height for the scaled image.
2064 * @param ratio
2065 * A height/width ratio used to determine the orientation of the
2066 * image so the primary dimension (width or height) can be
2067 * selected to test if it is greater than or less than a
2068 * particular threshold.
2069 *
2070 * @return the fastest {@link Method} suited for scaling the image to the
2071 * specified dimensions while maintaining a good-looking result.
2072 */
2073 protected static Method determineScalingMethod(int targetWidth,
2074 int targetHeight, float ratio) {
2075 // Get the primary dimension based on the orientation of the image
2076 int length = (ratio <= 1 ? targetWidth : targetHeight);
2077
2078 // Default to speed
2079 Method result = Method.SPEED;
2080
2081 // Figure out which scalingMethod should be used
2082 if (length <= Scalr.THRESHOLD_QUALITY_BALANCED)
2083 result = Method.QUALITY;
2084 else if (length <= Scalr.THRESHOLD_BALANCED_SPEED)
2085 result = Method.BALANCED;
2086
2087 if (DEBUG)
2088 log(2, "AUTOMATIC scaling method selected: %s", result.name());
2089
2090 return result;
2091 }
2092
2093 /**
2094 * Used to implement a straight-forward image-scaling operation using Java
2095 * 2D.
2096 * <p/>
2097 * This method uses the Oracle-encouraged method of
2098 * <code>Graphics2D.drawImage(...)</code> to scale the given image with the
2099 * given interpolation hint.
2100 *
2101 * @param src
2102 * The image that will be scaled.
2103 * @param targetWidth
2104 * The target width for the scaled image.
2105 * @param targetHeight
2106 * The target height for the scaled image.
2107 * @param interpolationHintValue
2108 * The {@link RenderingHints} interpolation value used to
2109 * indicate the method that {@link Graphics2D} should use when
2110 * scaling the image.
2111 *
2112 * @return the result of scaling the original <code>src</code> to the given
2113 * dimensions using the given interpolation method.
2114 */
2115 protected static BufferedImage scaleImage(BufferedImage src,
2116 int targetWidth, int targetHeight, Object interpolationHintValue) {
2117 // Setup the rendering resources to match the source image's
2118 BufferedImage result = createOptimalImage(src, targetWidth,
2119 targetHeight);
2120 Graphics2D resultGraphics = result.createGraphics();
2121
2122 // Scale the image to the new buffer using the specified rendering hint.
2123 resultGraphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
2124 interpolationHintValue);
2125 resultGraphics.drawImage(src, 0, 0, targetWidth, targetHeight, null);
2126
2127 // Just to be clean, explicitly dispose our temporary graphics object
2128 resultGraphics.dispose();
2129
2130 // Return the scaled image to the caller.
2131 return result;
2132 }
2133
2134 /**
2135 * Used to implement Chris Campbell's incremental-scaling algorithm: <a
2136 * href="http://today.java.net/pub/a/today/2007/04/03/perils
2137 * -of-image-getscaledinstance
2138 * .html">http://today.java.net/pub/a/today/2007/04/03/perils
2139 * -of-image-getscaledinstance.html</a>.
2140 * <p/>
2141 * Modifications to the original algorithm are variable names and comments
2142 * added for clarity and the hard-coding of using BICUBIC interpolation as
2143 * well as the explicit "flush()" operation on the interim BufferedImage
2144 * instances to avoid resource leaking.
2145 *
2146 * @param src
2147 * The image that will be scaled.
2148 * @param targetWidth
2149 * The target width for the scaled image.
2150 * @param targetHeight
2151 * The target height for the scaled image.
2152 * @param scalingMethod
2153 * The scaling method specified by the user (or calculated by
2154 * imgscalr) to use for this incremental scaling operation.
2155 * @param interpolationHintValue
2156 * The {@link RenderingHints} interpolation value used to
2157 * indicate the method that {@link Graphics2D} should use when
2158 * scaling the image.
2159 *
2160 * @return an image scaled to the given dimensions using the given rendering
2161 * hint.
2162 */
2163 protected static BufferedImage scaleImageIncrementally(BufferedImage src,
2164 int targetWidth, int targetHeight, Method scalingMethod,
2165 Object interpolationHintValue) {
2166 boolean hasReassignedSrc = false;
2167 int incrementCount = 0;
2168 int currentWidth = src.getWidth();
2169 int currentHeight = src.getHeight();
2170
2171 /*
2172 * The original QUALITY mode, representing Chris Campbell's algorithm,
2173 * is to step down by 1/2s every time when scaling the image
2174 * incrementally. Users pointed out that using this method to scale
2175 * images with noticeable straight lines left them really jagged in
2176 * smaller thumbnail format.
2177 *
2178 * After investigation it was discovered that scaling incrementally by
2179 * smaller increments was the ONLY way to make the thumbnail sized
2180 * images look less jagged and more accurate; almost matching the
2181 * accuracy of Mac's built in thumbnail generation which is the highest
2182 * quality resize I've come across (better than GIMP Lanczos3 and
2183 * Windows 7).
2184 *
2185 * A divisor of 7 was chose as using 5 still left some jaggedness in the
2186 * image while a divisor of 8 or higher made the resulting thumbnail too
2187 * soft; like our OP_ANTIALIAS convolve op had been forcibly applied to
2188 * the result even if the user didn't want it that soft.
2189 *
2190 * Using a divisor of 7 for the ULTRA_QUALITY seemed to be the sweet
2191 * spot.
2192 *
2193 * NOTE: Below when the actual fraction is used to calculate the small
2194 * portion to subtract from the current dimension, this is a
2195 * progressively smaller and smaller chunk. When the code was changed to
2196 * do a linear reduction of the image of equal steps for each
2197 * incremental resize (e.g. say 50px each time) the result was
2198 * significantly worse than the progressive approach used below; even
2199 * when a very high number of incremental steps (13) was tested.
2200 */
2201 int fraction = (scalingMethod == Method.ULTRA_QUALITY ? 7 : 2);
2202
2203 do {
2204 int prevCurrentWidth = currentWidth;
2205 int prevCurrentHeight = currentHeight;
2206
2207 /*
2208 * If the current width is bigger than our target, cut it in half
2209 * and sample again.
2210 */
2211 if (currentWidth > targetWidth) {
2212 currentWidth -= (currentWidth / fraction);
2213
2214 /*
2215 * If we cut the width too far it means we are on our last
2216 * iteration. Just set it to the target width and finish up.
2217 */
2218 if (currentWidth < targetWidth)
2219 currentWidth = targetWidth;
2220 }
2221
2222 /*
2223 * If the current height is bigger than our target, cut it in half
2224 * and sample again.
2225 */
2226
2227 if (currentHeight > targetHeight) {
2228 currentHeight -= (currentHeight / fraction);
2229
2230 /*
2231 * If we cut the height too far it means we are on our last
2232 * iteration. Just set it to the target height and finish up.
2233 */
2234
2235 if (currentHeight < targetHeight)
2236 currentHeight = targetHeight;
2237 }
2238
2239 /*
2240 * Stop when we cannot incrementally step down anymore.
2241 *
2242 * This used to use a || condition, but that would cause problems
2243 * when using FIT_EXACT such that sometimes the width OR height
2244 * would not change between iterations, but the other dimension
2245 * would (e.g. resizing 500x500 to 500x250).
2246 *
2247 * Now changing this to an && condition requires that both
2248 * dimensions do not change between a resize iteration before we
2249 * consider ourselves done.
2250 */
2251 if (prevCurrentWidth == currentWidth
2252 && prevCurrentHeight == currentHeight)
2253 break;
2254
2255 if (DEBUG)
2256 log(2, "Scaling from [%d x %d] to [%d x %d]", prevCurrentWidth,
2257 prevCurrentHeight, currentWidth, currentHeight);
2258
2259 // Render the incremental scaled image.
2260 BufferedImage incrementalImage = scaleImage(src, currentWidth,
2261 currentHeight, interpolationHintValue);
2262
2263 /*
2264 * Before re-assigning our interim (partially scaled)
2265 * incrementalImage to be the new src image before we iterate around
2266 * again to process it down further, we want to flush() the previous
2267 * src image IF (and only IF) it was one of our own temporary
2268 * BufferedImages created during this incremental down-sampling
2269 * cycle. If it wasn't one of ours, then it was the original
2270 * caller-supplied BufferedImage in which case we don't want to
2271 * flush() it and just leave it alone.
2272 */
2273 if (hasReassignedSrc)
2274 src.flush();
2275
2276 /*
2277 * Now treat our incremental partially scaled image as the src image
2278 * and cycle through our loop again to do another incremental
2279 * scaling of it (if necessary).
2280 */
2281 src = incrementalImage;
2282
2283 /*
2284 * Keep track of us re-assigning the original caller-supplied source
2285 * image with one of our interim BufferedImages so we know when to
2286 * explicitly flush the interim "src" on the next cycle through.
2287 */
2288 hasReassignedSrc = true;
2289
2290 // Track how many times we go through this cycle to scale the image.
2291 incrementCount++;
2292 } while (currentWidth != targetWidth || currentHeight != targetHeight);
2293
2294 if (DEBUG)
2295 log(2, "Incrementally Scaled Image in %d steps.", incrementCount);
2296
2297 /*
2298 * Once the loop has exited, the src image argument is now our scaled
2299 * result image that we want to return.
2300 */
2301 return src;
2302 }
2303 }