forked from Konloch/bytecode-viewer
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathScalr.java
More file actions
2333 lines (2185 loc) · 98.3 KB
/
Copy pathScalr.java
File metadata and controls
2333 lines (2185 loc) · 98.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Copyright 2011 The Buzz Media, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.imgscalr;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.color.ColorSpace;
import java.awt.geom.AffineTransform;
import java.awt.geom.Rectangle2D;
import java.awt.image.*;
/**
* Class used to implement performant, high-quality and intelligent image
* scaling and manipulation algorithms in native Java 2D.
* <p/>
* This class utilizes the Java2D "best practices" for image manipulation,
* ensuring that all operations (even most user-provided {@link BufferedImageOp}
* s) are hardware accelerated if provided by the platform and host-VM.
* <p/>
* <h3>Image Quality</h3>
* This class implements a few different methods for scaling an image, providing
* either the best-looking result, the fastest result or a balanced result
* between the two depending on the scaling hint provided (see {@link Method}).
* <p/>
* This class also implements an optimized version of the incremental scaling
* algorithm presented by Chris Campbell in his <a href="http://today.java
* .net/pub/a/today/2007/04/03/perils-of-image-getscaledinstance.html">Perils of
* Image.getScaledInstance()</a> article in order to give the best-looking image
* resize results (e.g. generating thumbnails that aren't blurry or jagged).
* <p>
* The results generated by imgscalr using this method, as compared to a single
* {@link RenderingHints#VALUE_INTERPOLATION_BICUBIC} scale operation look much
* better, especially when using the {@link Method#ULTRA_QUALITY} method.
* <p/>
* Only when scaling using the {@link Method#AUTOMATIC} method will this class
* look at the size of the image before selecting an approach to scaling the
* image. If {@link Method#QUALITY} is specified, the best-looking algorithm
* possible is always used.
* <p/>
* Minor modifications are made to Campbell's original implementation in the
* form of:
* <ol>
* <li>Instead of accepting a user-supplied interpolation method,
* {@link RenderingHints#VALUE_INTERPOLATION_BICUBIC} interpolation is always
* used. This was done after A/B comparison testing with large images
* down-scaled to thumbnail sizes showed noticeable "blurring" when BILINEAR
* interpolation was used. Given that Campbell's algorithm is only used in
* QUALITY mode when down-scaling, it was determined that the user's expectation
* of a much less blurry picture would require that BICUBIC be the default
* interpolation in order to meet the QUALITY expectation.</li>
* <li>After each iteration of the do-while loop that incrementally scales the
* source image down, an explicit effort is made to call
* {@link BufferedImage#flush()} on the interim temporary {@link BufferedImage}
* instances created by the algorithm in an attempt to ensure a more complete GC
* cycle by the VM when cleaning up the temporary instances (this is in addition
* to disposing of the temporary {@link Graphics2D} references as well).</li>
* <li>Extensive comments have been added to increase readability of the code.</li>
* <li>Variable names have been expanded to increase readability of the code.</li>
* </ol>
* <p/>
* <strong>NOTE</strong>: This class does not call {@link BufferedImage#flush()}
* on any of the <em>source images</em> passed in by calling code; it is up to
* the original caller to dispose of their source images when they are no longer
* needed so the VM can most efficiently GC them.
* <h3>Image Proportions</h3>
* All scaling operations implemented by this class maintain the proportions of
* the original image unless a mode of {@link Mode#FIT_EXACT} is specified; in
* which case the orientation and proportion of the source image is ignored and
* the image is stretched (if necessary) to fit the exact dimensions given.
* <p/>
* When not using {@link Mode#FIT_EXACT}, in order to maintain the
* proportionality of the original images, this class implements the following
* behavior:
* <ol>
* <li>If the image is LANDSCAPE-oriented or SQUARE, treat the
* <code>targetWidth</code> as the primary dimension and re-calculate the
* <code>targetHeight</code> regardless of what is passed in.</li>
* <li>If image is PORTRAIT-oriented, treat the <code>targetHeight</code> as the
* primary dimension and re-calculate the <code>targetWidth</code> regardless of
* what is passed in.</li>
* <li>If a {@link Mode} value of {@link Mode#FIT_TO_WIDTH} or
* {@link Mode#FIT_TO_HEIGHT} is passed in to the <code>resize</code> method,
* the image's orientation is ignored and the scaled image is fit to the
* preferred dimension by using the value passed in by the user for that
* dimension and recalculating the other (regardless of image orientation). This
* is useful, for example, when working with PORTRAIT oriented images that you
* need to all be the same width or visa-versa (e.g. showing user profile
* pictures in a directory listing).</li>
* </ol>
* <h3>Optimized Image Handling</h3>
* Java2D provides support for a number of different image types defined as
* <code>BufferedImage.TYPE_*</code> variables, unfortunately not all image
* types are supported equally in the Java2D rendering pipeline.
* <p/>
* Some more obscure image types either have poor or no support, leading to
* severely degraded quality and processing performance when an attempt is made
* by imgscalr to create a scaled instance <em>of the same type</em> as the
* source image. In many cases, especially when applying {@link BufferedImageOp}
* s, using poorly supported image types can even lead to exceptions or total
* corruption of the image (e.g. solid black image).
* <p/>
* imgscalr specifically accounts for and automatically hands
* <strong>ALL</strong> of these pain points for you internally by shuffling all
* images into one of two types:
* <ol>
* <li>{@link BufferedImage#TYPE_INT_RGB}</li>
* <li>{@link BufferedImage#TYPE_INT_ARGB}</li>
* </ol>
* depending on if the source image utilizes transparency or not. This is a
* recommended approach by the Java2D team for dealing with poorly (or non)
* supported image types. More can be read about this issue <a href=
* "http://www.mail-archive.com/java2d-interest@capra.eng.sun.com/msg05621.html"
* >here</a>.
* <p/>
* This is also the reason we recommend using
* {@link #apply(BufferedImage, BufferedImageOp...)} to apply your own ops to
* images even if you aren't using imgscalr for anything else.
* <h3>GIF Transparency</h3>
* Unfortunately in Java 6 and earlier, support for GIF's
* {@link IndexColorModel} is sub-par, both in accurate color-selection and in
* maintaining transparency when moving to an image of type
* {@link BufferedImage#TYPE_INT_ARGB}; because of this issue when a GIF image
* is processed by imgscalr and the result saved as a GIF file (instead of PNG),
* it is possible to lose the alpha channel of a transparent image or in the
* case of applying an optional {@link BufferedImageOp}, lose the entire picture
* all together in the result (long standing JDK bugs are filed for all of these
* issues).
* <p/>
* imgscalr currently does nothing to work around this manually because it is a
* defect in the native platform code itself. Fortunately it looks like the
* issues are half-fixed in Java 7 and any manual workarounds we could attempt
* internally are relatively expensive, in the form of hand-creating and setting
* RGB values pixel-by-pixel with a custom {@link ColorModel} in the scaled
* image. This would lead to a very measurable negative impact on performance
* without the caller understanding why.
* <p>
* <strong>Workaround</strong>: A workaround to this issue with all version of
* Java is to simply save a GIF as a PNG; no change to your code needs to be
* made except when the image is saved out, e.g. using {@link ImageIO}.
* <p>
* When a file type of "PNG" is used, both the transparency and high color
* quality will be maintained as the PNG code path in Java2D is superior to the
* GIF implementation.
* <p>
* If the issue with optional {@link BufferedImageOp}s destroying GIF image
* content is ever fixed in the platform, saving out resulting images as GIFs
* should suddenly start working.
* <p>
* More can be read about the issue <a
* href="http://gman.eichberger.de/2007/07/transparent-gifs-in-java.html"
* >here</a> and <a
* href="http://ubuntuforums.org/archive/index.php/t-1060128.html">here</a>.
* <h3>Thread Safety</h3>
* The {@link Scalr} class is <strong>thread-safe</strong> (as all the methods
* are <code>static</code>); this class maintains no internal state while
* performing any of the provided operations and is safe to call simultaneously
* from multiple threads.
* <h3>Logging</h3>
* This class implements all its debug logging via the
* {@link #log(int, String, Object...)} method. At this time logging is done
* directly to <code>System.out</code> via the <code>printf</code> method. This
* allows the logging to be light weight and easy to capture (every imgscalr log
* message is prefixed with the {@link #LOG_PREFIX} string) while adding no
* dependencies to the library.
* <p/>
* Implementation of logging in this class is as efficient as possible; avoiding
* any calls to the logger method or passing of arguments if logging is not
* enabled to avoid the (hidden) cost of constructing the Object[] argument for
* the varargs-based method call.
*
* @author Riyad Kalla (software@thebuzzmedia.com)
* @since 1.1
*/
public class Scalr {
/**
* System property name used to define the debug boolean flag.
* <p/>
* Value is "<code>imgscalr.debug</code>".
*/
public static final String DEBUG_PROPERTY_NAME = "imgscalr.debug";
/**
* System property name used to define a custom log prefix.
* <p/>
* Value is "<code>imgscalr.logPrefix</code>".
*/
public static final String LOG_PREFIX_PROPERTY_NAME = "imgscalr.logPrefix";
/**
* Flag used to indicate if debugging output has been enabled by setting the
* "<code>imgscalr.debug</code>" system property to <code>true</code>. This
* value will be <code>false</code> if the "<code>imgscalr.debug</code>"
* system property is undefined or set to <code>false</code>.
* <p/>
* This property can be set on startup with:<br/>
* <code>
* -Dimgscalr.debug=true
* </code> or by calling {@link System#setProperty(String, String)} to set a
* new property value for {@link #DEBUG_PROPERTY_NAME} before this class is
* loaded.
* <p/>
* Default value is <code>false</code>.
*/
public static final boolean DEBUG = Boolean.getBoolean(DEBUG_PROPERTY_NAME);
/**
* Prefix to every log message this library logs. Using a well-defined
* prefix helps make it easier both visually and programmatically to scan
* log files for messages produced by this library.
* <p/>
* This property can be set on startup with:<br/>
* <code>
* -Dimgscalr.logPrefix=<YOUR PREFIX HERE>
* </code> or by calling {@link System#setProperty(String, String)} to set a
* new property value for {@link #LOG_PREFIX_PROPERTY_NAME} before this
* class is loaded.
* <p/>
* Default value is "<code>[imgscalr] </code>" (including the space).
*/
public static final String LOG_PREFIX = System.getProperty(
LOG_PREFIX_PROPERTY_NAME, "[imgscalr] ");
/**
* A {@link ConvolveOp} using a very light "blur" kernel that acts like an
* anti-aliasing filter (softens the image a bit) when applied to an image.
* <p/>
* A common request by users of the library was that they wished to "soften"
* resulting images when scaling them down drastically. After quite a bit of
* A/B testing, the kernel used by this Op was selected as the closest match
* for the target which was the softer results from the deprecated
* {@link AreaAveragingScaleFilter} (which is used internally by the
* deprecated {@link Image#getScaledInstance(int, int, int)} method in the
* JDK that imgscalr is meant to replace).
* <p/>
* This ConvolveOp uses a 3x3 kernel with the values:
* <table cellpadding="4" border="1">
* <tr>
* <td>.0f</td>
* <td>.08f</td>
* <td>.0f</td>
* </tr>
* <tr>
* <td>.08f</td>
* <td>.68f</td>
* <td>.08f</td>
* </tr>
* <tr>
* <td>.0f</td>
* <td>.08f</td>
* <td>.0f</td>
* </tr>
* </table>
* <p/>
* For those that have worked with ConvolveOps before, this Op uses the
* {@link ConvolveOp#EDGE_NO_OP} instruction to not process the pixels along
* the very edge of the image (otherwise EDGE_ZERO_FILL would create a
* black-border around the image). If you have not worked with a ConvolveOp
* before, it just means this default OP will "do the right thing" and not
* give you garbage results.
* <p/>
* This ConvolveOp uses no {@link RenderingHints} values as internally the
* {@link ConvolveOp} class only uses hints when doing a color conversion
* between the source and destination {@link BufferedImage} targets.
* imgscalr allows the {@link ConvolveOp} to create its own destination
* image every time, so no color conversion is ever needed and thus no
* hints.
* <h3>Performance</h3>
* Use of this (and other) {@link ConvolveOp}s are hardware accelerated when
* possible. For more information on if your image op is hardware
* accelerated or not, check the source code of the underlying JDK class
* that actually executes the Op code, <a href=
* "http://www.docjar.com/html/api/sun/awt/image/ImagingLib.java.html"
* >sun.awt.image.ImagingLib</a>.
* <h3>Known Issues</h3>
* In all versions of Java (tested up to Java 7 preview Build 131), running
* this op against a GIF with transparency and attempting to save the
* resulting image as a GIF results in a corrupted/empty file. The file must
* be saved out as a PNG to maintain the transparency.
*
* @since 3.0
*/
public static final ConvolveOp OP_ANTIALIAS = new ConvolveOp(
new Kernel(3, 3, new float[] { .0f, .08f, .0f, .08f, .68f, .08f,
.0f, .08f, .0f }), ConvolveOp.EDGE_NO_OP, null);
/**
* A {@link RescaleOp} used to make any input image 10% darker.
* <p/>
* This operation can be applied multiple times in a row if greater than 10%
* changes in brightness are desired.
*
* @since 4.0
*/
public static final RescaleOp OP_DARKER = new RescaleOp(0.9f, 0, null);
/**
* A {@link RescaleOp} used to make any input image 10% brighter.
* <p/>
* This operation can be applied multiple times in a row if greater than 10%
* changes in brightness are desired.
*
* @since 4.0
*/
public static final RescaleOp OP_BRIGHTER = new RescaleOp(1.1f, 0, null);
/**
* A {@link ColorConvertOp} used to convert any image to a grayscale color
* palette.
* <p/>
* Applying this op multiple times to the same image has no compounding
* effects.
*
* @since 4.0
*/
public static final ColorConvertOp OP_GRAYSCALE = new ColorConvertOp(
ColorSpace.getInstance(ColorSpace.CS_GRAY), null);
/**
* Static initializer used to prepare some of the variables used by this
* class.
*/
static {
log(0, "Debug output ENABLED");
}
/**
* Used to define the different scaling hints that the algorithm can use.
*
* @author Riyad Kalla (software@thebuzzmedia.com)
* @since 1.1
*/
public static enum Method {
/**
* Used to indicate that the scaling implementation should decide which
* method to use in order to get the best looking scaled image in the
* least amount of time.
* <p/>
* The scaling algorithm will use the
* {@link Scalr#THRESHOLD_QUALITY_BALANCED} or
* {@link Scalr#THRESHOLD_BALANCED_SPEED} thresholds as cut-offs to
* decide between selecting the <code>QUALITY</code>,
* <code>BALANCED</code> or <code>SPEED</code> scaling algorithms.
* <p/>
* By default the thresholds chosen will give nearly the best looking
* result in the fastest amount of time. We intend this method to work
* for 80% of people looking to scale an image quickly and get a good
* looking result.
*/
AUTOMATIC,
/**
* Used to indicate that the scaling implementation should scale as fast
* as possible and return a result. For smaller images (800px in size)
* this can result in noticeable aliasing but it can be a few magnitudes
* times faster than using the QUALITY method.
*/
SPEED,
/**
* Used to indicate that the scaling implementation should use a scaling
* operation balanced between SPEED and QUALITY. Sometimes SPEED looks
* too low quality to be useful (e.g. text can become unreadable when
* scaled using SPEED) but using QUALITY mode will increase the
* processing time too much. This mode provides a "better than SPEED"
* quality in a "less than QUALITY" amount of time.
*/
BALANCED,
/**
* Used to indicate that the scaling implementation should do everything
* it can to create as nice of a result as possible. This approach is
* most important for smaller pictures (800px or smaller) and less
* important for larger pictures as the difference between this method
* and the SPEED method become less and less noticeable as the
* source-image size increases. Using the AUTOMATIC method will
* automatically prefer the QUALITY method when scaling an image down
* below 800px in size.
*/
QUALITY,
/**
* Used to indicate that the scaling implementation should go above and
* beyond the work done by {@link Method#QUALITY} to make the image look
* exceptionally good at the cost of more processing time. This is
* especially evident when generating thumbnails of images that look
* jagged with some of the other {@link Method}s (even
* {@link Method#QUALITY}).
*/
ULTRA_QUALITY;
}
/**
* Used to define the different modes of resizing that the algorithm can
* use.
*
* @author Riyad Kalla (software@thebuzzmedia.com)
* @since 3.1
*/
public static enum Mode {
/**
* Used to indicate that the scaling implementation should calculate
* dimensions for the resultant image by looking at the image's
* orientation and generating proportional dimensions that best fit into
* the target width and height given
*
* See "Image Proportions" in the {@link Scalr} class description for
* more detail.
*/
AUTOMATIC,
/**
* Used to fit the image to the exact dimensions given regardless of the
* image's proportions. If the dimensions are not proportionally
* correct, this will introduce vertical or horizontal stretching to the
* image.
* <p/>
* It is recommended that you use one of the other <code>FIT_TO</code>
* modes or {@link Mode#AUTOMATIC} if you want the image to look
* correct, but if dimension-fitting is the #1 priority regardless of
* how it makes the image look, that is what this mode is for.
*/
FIT_EXACT,
/**
* Used to indicate that the scaling implementation should calculate
* dimensions for the largest image that fit within the bounding box,
* without cropping or distortion, retaining the original proportions.
*/
BEST_FIT_BOTH,
/**
* Used to indicate that the scaling implementation should calculate
* dimensions for the resultant image that best-fit within the given
* width, regardless of the orientation of the image.
*/
FIT_TO_WIDTH,
/**
* Used to indicate that the scaling implementation should calculate
* dimensions for the resultant image that best-fit within the given
* height, regardless of the orientation of the image.
*/
FIT_TO_HEIGHT;
}
/**
* Used to define the different types of rotations that can be applied to an
* image during a resize operation.
*
* @author Riyad Kalla (software@thebuzzmedia.com)
* @since 3.2
*/
public static enum Rotation {
/**
* 90-degree, clockwise rotation (to the right). This is equivalent to a
* quarter-turn of the image to the right; moving the picture on to its
* right side.
*/
CW_90,
/**
* 180-degree, clockwise rotation (to the right). This is equivalent to
* 1 half-turn of the image to the right; rotating the picture around
* until it is upside down from the original position.
*/
CW_180,
/**
* 270-degree, clockwise rotation (to the right). This is equivalent to
* a quarter-turn of the image to the left; moving the picture on to its
* left side.
*/
CW_270,
/**
* Flip the image horizontally by reflecting it around the y axis.
* <p/>
* This is not a standard rotation around a center point, but instead
* creates the mirrored reflection of the image horizontally.
* <p/>
* More specifically, the vertical orientation of the image stays the
* same (the top stays on top, and the bottom on bottom), but the right
* and left sides flip. This is different than a standard rotation where
* the top and bottom would also have been flipped.
*/
FLIP_HORZ,
/**
* Flip the image vertically by reflecting it around the x axis.
* <p/>
* This is not a standard rotation around a center point, but instead
* creates the mirrored reflection of the image vertically.
* <p/>
* More specifically, the horizontal orientation of the image stays the
* same (the left stays on the left and the right stays on the right),
* but the top and bottom sides flip. This is different than a standard
* rotation where the left and right would also have been flipped.
*/
FLIP_VERT;
}
/**
* Threshold (in pixels) at which point the scaling operation using the
* {@link Method#AUTOMATIC} method will decide if a {@link Method#BALANCED}
* method will be used (if smaller than or equal to threshold) or a
* {@link Method#SPEED} method will be used (if larger than threshold).
* <p/>
* The bigger the image is being scaled to, the less noticeable degradations
* in the image becomes and the faster algorithms can be selected.
* <p/>
* The value of this threshold (1600) was chosen after visual, by-hand, A/B
* testing between different types of images scaled with this library; both
* photographs and screenshots. It was determined that images below this
* size need to use a {@link Method#BALANCED} scale method to look decent in
* most all cases while using the faster {@link Method#SPEED} method for
* images bigger than this threshold showed no noticeable degradation over a
* <code>BALANCED</code> scale.
*/
public static final int THRESHOLD_BALANCED_SPEED = 1600;
/**
* Threshold (in pixels) at which point the scaling operation using the
* {@link Method#AUTOMATIC} method will decide if a {@link Method#QUALITY}
* method will be used (if smaller than or equal to threshold) or a
* {@link Method#BALANCED} method will be used (if larger than threshold).
* <p/>
* The bigger the image is being scaled to, the less noticeable degradations
* in the image becomes and the faster algorithms can be selected.
* <p/>
* The value of this threshold (800) was chosen after visual, by-hand, A/B
* testing between different types of images scaled with this library; both
* photographs and screenshots. It was determined that images below this
* size need to use a {@link Method#QUALITY} scale method to look decent in
* most all cases while using the faster {@link Method#BALANCED} method for
* images bigger than this threshold showed no noticeable degradation over a
* <code>QUALITY</code> scale.
*/
public static final int THRESHOLD_QUALITY_BALANCED = 800;
/**
* Used to apply, in the order given, 1 or more {@link BufferedImageOp}s to
* a given {@link BufferedImage} and return the result.
* <p/>
* <strong>Feature</strong>: This implementation works around <a
* href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4965606">a
* decade-old JDK bug</a> that can cause a {@link RasterFormatException}
* when applying a perfectly valid {@link BufferedImageOp}s to images.
* <p/>
* <strong>Feature</strong>: This implementation also works around
* {@link BufferedImageOp}s failing to apply and throwing
* {@link ImagingOpException}s when run against a <code>src</code> image
* type that is poorly supported. Unfortunately using {@link ImageIO} and
* standard Java methods to load images provides no consistency in getting
* images in well-supported formats. This method automatically accounts and
* corrects for all those problems (if necessary).
* <p/>
* It is recommended you always use this method to apply any
* {@link BufferedImageOp}s instead of relying on directly using the
* {@link BufferedImageOp#filter(BufferedImage, BufferedImage)} method.
* <p/>
* <strong>Performance</strong>: Not all {@link BufferedImageOp}s are
* hardware accelerated operations, but many of the most popular (like
* {@link ConvolveOp}) are. For more information on if your image op is
* hardware accelerated or not, check the source code of the underlying JDK
* class that actually executes the Op code, <a href=
* "http://www.docjar.com/html/api/sun/awt/image/ImagingLib.java.html"
* >sun.awt.image.ImagingLib</a>.
* <p/>
* <strong>TIP</strong>: This operation leaves the original <code>src</code>
* image unmodified. If the caller is done with the <code>src</code> image
* after getting the result of this operation, remember to call
* {@link BufferedImage#flush()} on the <code>src</code> to free up native
* resources and make it easier for the GC to collect the unused image.
*
* @param src
* The image that will have the ops applied to it.
* @param ops
* <code>1</code> or more ops to apply to the image.
*
* @return a new {@link BufferedImage} that represents the <code>src</code>
* with all the given operations applied to it.
*
* @throws IllegalArgumentException
* if <code>src</code> is <code>null</code>.
* @throws IllegalArgumentException
* if <code>ops</code> is <code>null</code> or empty.
* @throws ImagingOpException
* if one of the given {@link BufferedImageOp}s fails to apply.
* These exceptions bubble up from the inside of most of the
* {@link BufferedImageOp} implementations and are explicitly
* defined on the imgscalr API to make it easier for callers to
* catch the exception (if they are passing along optional ops
* to be applied). imgscalr takes detailed steps to avoid the
* most common pitfalls that will cause {@link BufferedImageOp}s
* to fail, even when using straight forward JDK-image
* operations.
*/
public static BufferedImage apply(BufferedImage src, BufferedImageOp... ops)
throws IllegalArgumentException, ImagingOpException {
long t = -1;
if (DEBUG)
t = System.currentTimeMillis();
if (src == null)
throw new IllegalArgumentException("src cannot be null");
if (ops == null || ops.length == 0)
throw new IllegalArgumentException("ops cannot be null or empty");
int type = src.getType();
/*
* Ensure the src image is in the best supported image type before we
* continue, otherwise it is possible our calls below to getBounds2D and
* certainly filter(...) may fail if not.
*
* Java2D makes an attempt at applying most BufferedImageOps using
* hardware acceleration via the ImagingLib internal library.
*
* Unfortunately may of the BufferedImageOp are written to simply fail
* with an ImagingOpException if the operation cannot be applied with no
* additional information about what went wrong or attempts at
* re-applying it in different ways.
*
* This is assuming the failing BufferedImageOp even returns a null
* image after failing to apply; some simply return a corrupted/black
* image that result in no exception and it is up to the user to
* discover this.
*
* In internal testing, EVERY failure I've ever seen was the result of
* the source image being in a poorly-supported BufferedImage Type like
* BGR or ABGR (even though it was loaded with ImageIO).
*
* To avoid this nasty/stupid surprise with BufferedImageOps, we always
* ensure that the src image starts in an optimally supported format
* before we try and apply the filter.
*/
if (!(type == BufferedImage.TYPE_INT_RGB || type == BufferedImage.TYPE_INT_ARGB))
src = copyToOptimalImage(src);
if (DEBUG)
log(0, "Applying %d BufferedImageOps...", ops.length);
boolean hasReassignedSrc = false;
for (int i = 0; i < ops.length; i++) {
long subT = -1;
if (DEBUG)
subT = System.currentTimeMillis();
BufferedImageOp op = ops[i];
// Skip null ops instead of throwing an exception.
if (op == null)
continue;
if (DEBUG)
log(1, "Applying BufferedImageOp [class=%s, toString=%s]...",
op.getClass(), op.toString());
/*
* Must use op.getBounds instead of src.getWidth and src.getHeight
* because we are trying to create an image big enough to hold the
* result of this operation (which may be to scale the image
* smaller), in that case the bounds reported by this op and the
* bounds reported by the source image will be different.
*/
Rectangle2D resultBounds = op.getBounds2D(src);
// Watch out for flaky/misbehaving ops that fail to work right.
if (resultBounds == null)
throw new ImagingOpException(
"BufferedImageOp ["
+ op.toString()
+ "] getBounds2D(src) returned null bounds for the target image; this should not happen and indicates a problem with application of this type of op.");
/*
* We must manually create the target image; we cannot rely on the
* null-destination filter() method to create a valid destination
* for us thanks to this JDK bug that has been filed for almost a
* decade:
* http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4965606
*/
BufferedImage dest = createOptimalImage(src,
(int) Math.round(resultBounds.getWidth()),
(int) Math.round(resultBounds.getHeight()));
// Perform the operation, update our result to return.
BufferedImage result = op.filter(src, dest);
/*
* Flush the 'src' image ONLY IF it is one of our interim temporary
* images being used when applying 2 or more operations back to
* back. We never want to flush the original image passed in.
*/
if (hasReassignedSrc)
src.flush();
/*
* Incase there are more operations to perform, update what we
* consider the 'src' reference to our last result so on the next
* iteration the next op is applied to this result and not back
* against the original src passed in.
*/
src = result;
/*
* Keep track of when we re-assign 'src' to an interim temporary
* image, so we know when we can explicitly flush it and clean up
* references on future iterations.
*/
hasReassignedSrc = true;
if (DEBUG)
log(1,
"Applied BufferedImageOp in %d ms, result [width=%d, height=%d]",
System.currentTimeMillis() - subT, result.getWidth(),
result.getHeight());
}
if (DEBUG)
log(0, "All %d BufferedImageOps applied in %d ms", ops.length,
System.currentTimeMillis() - t);
return src;
}
/**
* Used to crop the given <code>src</code> image from the top-left corner
* and applying any optional {@link BufferedImageOp}s to the result before
* returning it.
* <p/>
* <strong>TIP</strong>: This operation leaves the original <code>src</code>
* image unmodified. If the caller is done with the <code>src</code> image
* after getting the result of this operation, remember to call
* {@link BufferedImage#flush()} on the <code>src</code> to free up native
* resources and make it easier for the GC to collect the unused image.
*
* @param src
* The image to crop.
* @param width
* The width of the bounding cropping box.
* @param height
* The height of the bounding cropping box.
* @param ops
* <code>0</code> or more ops to apply to the image. If
* <code>null</code> or empty then <code>src</code> is return
* unmodified.
*
* @return a new {@link BufferedImage} representing the cropped region of
* the <code>src</code> image with any optional operations applied
* to it.
*
* @throws IllegalArgumentException
* if <code>src</code> is <code>null</code>.
* @throws IllegalArgumentException
* if any coordinates of the bounding crop box is invalid within
* the bounds of the <code>src</code> image (e.g. negative or
* too big).
* @throws ImagingOpException
* if one of the given {@link BufferedImageOp}s fails to apply.
* These exceptions bubble up from the inside of most of the
* {@link BufferedImageOp} implementations and are explicitly
* defined on the imgscalr API to make it easier for callers to
* catch the exception (if they are passing along optional ops
* to be applied). imgscalr takes detailed steps to avoid the
* most common pitfalls that will cause {@link BufferedImageOp}s
* to fail, even when using straight forward JDK-image
* operations.
*/
public static BufferedImage crop(BufferedImage src, int width, int height,
BufferedImageOp... ops) throws IllegalArgumentException,
ImagingOpException {
return crop(src, 0, 0, width, height, ops);
}
/**
* Used to crop the given <code>src</code> image and apply any optional
* {@link BufferedImageOp}s to it before returning the result.
* <p/>
* <strong>TIP</strong>: This operation leaves the original <code>src</code>
* image unmodified. If the caller is done with the <code>src</code> image
* after getting the result of this operation, remember to call
* {@link BufferedImage#flush()} on the <code>src</code> to free up native
* resources and make it easier for the GC to collect the unused image.
*
* @param src
* The image to crop.
* @param x
* The x-coordinate of the top-left corner of the bounding box
* used for cropping.
* @param y
* The y-coordinate of the top-left corner of the bounding box
* used for cropping.
* @param width
* The width of the bounding cropping box.
* @param height
* The height of the bounding cropping box.
* @param ops
* <code>0</code> or more ops to apply to the image. If
* <code>null</code> or empty then <code>src</code> is return
* unmodified.
*
* @return a new {@link BufferedImage} representing the cropped region of
* the <code>src</code> image with any optional operations applied
* to it.
*
* @throws IllegalArgumentException
* if <code>src</code> is <code>null</code>.
* @throws IllegalArgumentException
* if any coordinates of the bounding crop box is invalid within
* the bounds of the <code>src</code> image (e.g. negative or
* too big).
* @throws ImagingOpException
* if one of the given {@link BufferedImageOp}s fails to apply.
* These exceptions bubble up from the inside of most of the
* {@link BufferedImageOp} implementations and are explicitly
* defined on the imgscalr API to make it easier for callers to
* catch the exception (if they are passing along optional ops
* to be applied). imgscalr takes detailed steps to avoid the
* most common pitfalls that will cause {@link BufferedImageOp}s
* to fail, even when using straight forward JDK-image
* operations.
*/
public static BufferedImage crop(BufferedImage src, int x, int y,
int width, int height, BufferedImageOp... ops)
throws IllegalArgumentException, ImagingOpException {
long t = -1;
if (DEBUG)
t = System.currentTimeMillis();
if (src == null)
throw new IllegalArgumentException("src cannot be null");
if (x < 0 || y < 0 || width < 0 || height < 0)
throw new IllegalArgumentException("Invalid crop bounds: x [" + x
+ "], y [" + y + "], width [" + width + "] and height ["
+ height + "] must all be >= 0");
int srcWidth = src.getWidth();
int srcHeight = src.getHeight();
if ((x + width) > srcWidth)
throw new IllegalArgumentException(
"Invalid crop bounds: x + width [" + (x + width)
+ "] must be <= src.getWidth() [" + srcWidth + "]");
if ((y + height) > srcHeight)
throw new IllegalArgumentException(
"Invalid crop bounds: y + height [" + (y + height)
+ "] must be <= src.getHeight() [" + srcHeight
+ "]");
if (DEBUG)
log(0,
"Cropping Image [width=%d, height=%d] to [x=%d, y=%d, width=%d, height=%d]...",
srcWidth, srcHeight, x, y, width, height);
// Create a target image of an optimal type to render into.
BufferedImage result = createOptimalImage(src, width, height);
Graphics g = result.getGraphics();
/*
* Render the region specified by our crop bounds from the src image
* directly into our result image (which is the exact size of the crop
* region).
*/
g.drawImage(src, 0, 0, width, height, x, y, (x + width), (y + height),
null);
g.dispose();
if (DEBUG)
log(0, "Cropped Image in %d ms", System.currentTimeMillis() - t);
// Apply any optional operations (if specified).
if (ops != null && ops.length > 0)
result = apply(result, ops);
return result;
}
/**
* Used to apply padding around the edges of an image using
* {@link Color#BLACK} to fill the extra padded space and then return the
* result.
* <p/>
* The amount of <code>padding</code> specified is applied to all sides;
* more specifically, a <code>padding</code> of <code>2</code> would add 2
* extra pixels of space (filled by the given <code>color</code>) on the
* top, bottom, left and right sides of the resulting image causing the
* result to be 4 pixels wider and 4 pixels taller than the <code>src</code>
* image.
* <p/>
* <strong>TIP</strong>: This operation leaves the original <code>src</code>
* image unmodified. If the caller is done with the <code>src</code> image
* after getting the result of this operation, remember to call
* {@link BufferedImage#flush()} on the <code>src</code> to free up native
* resources and make it easier for the GC to collect the unused image.
*
* @param src
* The image the padding will be added to.
* @param padding
* The number of pixels of padding to add to each side in the
* resulting image. If this value is <code>0</code> then
* <code>src</code> is returned unmodified.
* @param ops
* <code>0</code> or more ops to apply to the image. If
* <code>null</code> or empty then <code>src</code> is return
* unmodified.
*
* @return a new {@link BufferedImage} representing <code>src</code> with
* the given padding applied to it.
*
* @throws IllegalArgumentException
* if <code>src</code> is <code>null</code>.
* @throws IllegalArgumentException
* if <code>padding</code> is < <code>1</code>.
* @throws ImagingOpException
* if one of the given {@link BufferedImageOp}s fails to apply.
* These exceptions bubble up from the inside of most of the
* {@link BufferedImageOp} implementations and are explicitly
* defined on the imgscalr API to make it easier for callers to
* catch the exception (if they are passing along optional ops
* to be applied). imgscalr takes detailed steps to avoid the
* most common pitfalls that will cause {@link BufferedImageOp}s
* to fail, even when using straight forward JDK-image
* operations.
*/
public static BufferedImage pad(BufferedImage src, int padding,
BufferedImageOp... ops) throws IllegalArgumentException,
ImagingOpException {
return pad(src, padding, Color.BLACK);
}
/**
* Used to apply padding around the edges of an image using the given color
* to fill the extra padded space and then return the result. {@link Color}s
* using an alpha channel (i.e. transparency) are supported.
* <p/>
* The amount of <code>padding</code> specified is applied to all sides;
* more specifically, a <code>padding</code> of <code>2</code> would add 2
* extra pixels of space (filled by the given <code>color</code>) on the
* top, bottom, left and right sides of the resulting image causing the
* result to be 4 pixels wider and 4 pixels taller than the <code>src</code>
* image.
* <p/>
* <strong>TIP</strong>: This operation leaves the original <code>src</code>
* image unmodified. If the caller is done with the <code>src</code> image
* after getting the result of this operation, remember to call
* {@link BufferedImage#flush()} on the <code>src</code> to free up native
* resources and make it easier for the GC to collect the unused image.
*
* @param src
* The image the padding will be added to.
* @param padding
* The number of pixels of padding to add to each side in the
* resulting image. If this value is <code>0</code> then
* <code>src</code> is returned unmodified.
* @param color
* The color to fill the padded space with. {@link Color}s using
* an alpha channel (i.e. transparency) are supported.
* @param ops
* <code>0</code> or more ops to apply to the image. If
* <code>null</code> or empty then <code>src</code> is return
* unmodified.
*
* @return a new {@link BufferedImage} representing <code>src</code> with
* the given padding applied to it.
*
* @throws IllegalArgumentException
* if <code>src</code> is <code>null</code>.
* @throws IllegalArgumentException
* if <code>padding</code> is < <code>1</code>.
* @throws IllegalArgumentException
* if <code>color</code> is <code>null</code>.
* @throws ImagingOpException
* if one of the given {@link BufferedImageOp}s fails to apply.
* These exceptions bubble up from the inside of most of the
* {@link BufferedImageOp} implementations and are explicitly
* defined on the imgscalr API to make it easier for callers to
* catch the exception (if they are passing along optional ops
* to be applied). imgscalr takes detailed steps to avoid the
* most common pitfalls that will cause {@link BufferedImageOp}s
* to fail, even when using straight forward JDK-image
* operations.
*/
public static BufferedImage pad(BufferedImage src, int padding,
Color color, BufferedImageOp... ops)
throws IllegalArgumentException, ImagingOpException {
long t = -1;
if (DEBUG)
t = System.currentTimeMillis();
if (src == null)
throw new IllegalArgumentException("src cannot be null");
if (padding < 1)
throw new IllegalArgumentException("padding [" + padding
+ "] must be > 0");
if (color == null)
throw new IllegalArgumentException("color cannot be null");
int srcWidth = src.getWidth();
int srcHeight = src.getHeight();