Class Scalr
- java.lang.Object
-
- org.imgscalr.Scalr
-
public class Scalr extends Object
Class used to implement performant, high-quality and intelligent image scaling and manipulation algorithms in native Java 2D. This class utilizes the Java2D "best practices" for image manipulation, ensuring that all operations (even most user-providedBufferedImageOps) are hardware accelerated if provided by the platform and host-VM.Image Quality
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 (seeScalr.Method). This class also implements an optimized version of the incremental scaling algorithm presented by Chris Campbell in his Perils of Image.getScaledInstance() article in order to give the best-looking image resize results (e.g. generating thumbnails that aren't blurry or jagged).The results generated by imgscalr using this method, as compared to a single
Only when scaling using theRenderingHints.VALUE_INTERPOLATION_BICUBICscale operation look much better, especially when using theScalr.Method.ULTRA_QUALITYmethod.Scalr.Method.AUTOMATICmethod will this class look at the size of the image before selecting an approach to scaling the image. IfScalr.Method.QUALITYis specified, the best-looking algorithm possible is always used. Minor modifications are made to Campbell's original implementation in the form of:- Instead of accepting a user-supplied interpolation method,
RenderingHints.VALUE_INTERPOLATION_BICUBICinterpolation 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. - After each iteration of the do-while loop that incrementally scales the
source image down, an explicit effort is made to call
Image.flush()on the interim temporaryBufferedImageinstances 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 temporaryGraphics2Dreferences as well). - Extensive comments have been added to increase readability of the code.
- Variable names have been expanded to increase readability of the code.
Image.flush()on any of the source images 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.Image Proportions
All scaling operations implemented by this class maintain the proportions of the original image unless a mode ofScalr.Mode.FIT_EXACTis 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. When not usingScalr.Mode.FIT_EXACT, in order to maintain the proportionality of the original images, this class implements the following behavior:- If the image is LANDSCAPE-oriented or SQUARE, treat the
targetWidthas the primary dimension and re-calculate thetargetHeightregardless of what is passed in. - If image is PORTRAIT-oriented, treat the
targetHeightas the primary dimension and re-calculate thetargetWidthregardless of what is passed in. - If a
Scalr.Modevalue ofScalr.Mode.FIT_TO_WIDTHorScalr.Mode.FIT_TO_HEIGHTis passed in to theresizemethod, 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).
Optimized Image Handling
Java2D provides support for a number of different image types defined asBufferedImage.TYPE_*variables, unfortunately not all image types are supported equally in the Java2D rendering pipeline. 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 of the same type as the source image. In many cases, especially when applyingBufferedImageOps, using poorly supported image types can even lead to exceptions or total corruption of the image (e.g. solid black image). imgscalr specifically accounts for and automatically hands ALL of these pain points for you internally by shuffling all images into one of two types: 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 here. This is also the reason we recommend usingapply(BufferedImage, BufferedImageOp...)to apply your own ops to images even if you aren't using imgscalr for anything else.GIF Transparency
Unfortunately in Java 6 and earlier, support for GIF'sIndexColorModelis sub-par, both in accurate color-selection and in maintaining transparency when moving to an image of typeBufferedImage.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 optionalBufferedImageOp, lose the entire picture all together in the result (long standing JDK bugs are filed for all of these issues). 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 customColorModelin the scaled image. This would lead to a very measurable negative impact on performance without the caller understanding why.Workaround: 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
ImageIO.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.
If the issue with optional
BufferedImageOps destroying GIF image content is ever fixed in the platform, saving out resulting images as GIFs should suddenly start working.More can be read about the issue here and here.
Thread Safety
TheScalrclass is thread-safe (as all the methods arestatic); this class maintains no internal state while performing any of the provided operations and is safe to call simultaneously from multiple threads.Logging
This class implements all its debug logging via thelog(int, String, Object...)method. At this time logging is done directly toSystem.outvia theprintfmethod. This allows the logging to be light weight and easy to capture (every imgscalr log message is prefixed with theLOG_PREFIXstring) while adding no dependencies to the library. 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.- Since:
- 1.1
- Author:
- Riyad Kalla (software@thebuzzmedia.com)
- Instead of accepting a user-supplied interpolation method,
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description static classScalr.MethodUsed to define the different scaling hints that the algorithm can use.static classScalr.ModeUsed to define the different modes of resizing that the algorithm can use.static classScalr.RotationUsed to define the different types of rotations that can be applied to an image during a resize operation.
-
Field Summary
Fields Modifier and Type Field Description static booleanDEBUGFlag used to indicate if debugging output has been enabled by setting the "imgscalr.debug" system property totrue.static StringDEBUG_PROPERTY_NAMESystem property name used to define the debug boolean flag.static StringLOG_PREFIXPrefix to every log message this library logs.static StringLOG_PREFIX_PROPERTY_NAMESystem property name used to define a custom log prefix.static ConvolveOpOP_ANTIALIASAConvolveOpusing a very light "blur" kernel that acts like an anti-aliasing filter (softens the image a bit) when applied to an image.static RescaleOpOP_BRIGHTERARescaleOpused to make any input image 10% brighter.static RescaleOpOP_DARKERARescaleOpused to make any input image 10% darker.static ColorConvertOpOP_GRAYSCALEAColorConvertOpused to convert any image to a grayscale color palette.static intTHRESHOLD_BALANCED_SPEEDThreshold (in pixels) at which point the scaling operation using theScalr.Method.AUTOMATICmethod will decide if aScalr.Method.BALANCEDmethod will be used (if smaller than or equal to threshold) or aScalr.Method.SPEEDmethod will be used (if larger than threshold).static intTHRESHOLD_QUALITY_BALANCEDThreshold (in pixels) at which point the scaling operation using theScalr.Method.AUTOMATICmethod will decide if aScalr.Method.QUALITYmethod will be used (if smaller than or equal to threshold) or aScalr.Method.BALANCEDmethod will be used (if larger than threshold).
-
Constructor Summary
Constructors Constructor Description Scalr()
-
Method Summary
All Methods Static Methods Concrete Methods Modifier and Type Method Description static BufferedImageapply(BufferedImage src, BufferedImageOp... ops)Used to apply, in the order given, 1 or moreBufferedImageOps to a givenBufferedImageand return the result.protected static BufferedImagecopyToOptimalImage(BufferedImage src)Used to copy aBufferedImagefrom a non-optimal type into a newBufferedImageinstance of an optimal type (RGB or ARGB).protected static BufferedImagecreateOptimalImage(BufferedImage src)Used to create aBufferedImagewith the most optimal RGB TYPE (BufferedImage.TYPE_INT_RGBorBufferedImage.TYPE_INT_ARGB) capable of being rendered into from the givensrc.protected static BufferedImagecreateOptimalImage(BufferedImage src, int width, int height)Used to create aBufferedImagewith the given dimensions and the most optimal RGB TYPE (BufferedImage.TYPE_INT_RGBorBufferedImage.TYPE_INT_ARGB) capable of being rendered into from the givensrc.static BufferedImagecrop(BufferedImage src, int x, int y, int width, int height, BufferedImageOp... ops)Used to crop the givensrcimage and apply any optionalBufferedImageOps to it before returning the result.static BufferedImagecrop(BufferedImage src, int width, int height, BufferedImageOp... ops)Used to crop the givensrcimage from the top-left corner and applying any optionalBufferedImageOps to the result before returning it.protected static Scalr.MethoddetermineScalingMethod(int targetWidth, int targetHeight, float ratio)Used to determine the scalingScalr.Methodthat is best suited for scaling the image to the targeted dimensions.protected static voidlog(int depth, String message, Object... params)Used to write out a useful and well-formatted log message by any piece of code inside of the imgscalr library.static BufferedImagepad(BufferedImage src, int padding, Color color, BufferedImageOp... ops)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.static BufferedImagepad(BufferedImage src, int padding, BufferedImageOp... ops)Used to apply padding around the edges of an image usingColor.BLACKto fill the extra padded space and then return the result.static BufferedImageresize(BufferedImage src, int targetWidth, int targetHeight, BufferedImageOp... ops)Resize a given image (maintaining its original proportion) to the target width and height and apply the givenBufferedImageOps (if any) to the result before returning it.static BufferedImageresize(BufferedImage src, int targetSize, BufferedImageOp... ops)Resize a given image (maintaining its original proportion) to a width and height no bigger thantargetSizeand apply the givenBufferedImageOps (if any) to the result before returning it.static BufferedImageresize(BufferedImage src, Scalr.Method scalingMethod, int targetWidth, int targetHeight, BufferedImageOp... ops)Resize a given image (maintaining its original proportion) to the target width and height using the given scaling method and apply the givenBufferedImageOps (if any) to the result before returning it.static BufferedImageresize(BufferedImage src, Scalr.Method scalingMethod, int targetSize, BufferedImageOp... ops)Resize a given image (maintaining its original proportion) to a width and height no bigger thantargetSizeusing the given scaling method and apply the givenBufferedImageOps (if any) to the result before returning it.static BufferedImageresize(BufferedImage src, Scalr.Method scalingMethod, Scalr.Mode resizeMode, int targetWidth, int targetHeight, BufferedImageOp... ops)Resize a given image (maintaining its original proportion) to the target width and height (or fitting the image to the given WIDTH or HEIGHT explicitly, depending on theScalr.Modespecified) using the given scaling method and apply the givenBufferedImageOps (if any) to the result before returning it.static BufferedImageresize(BufferedImage src, Scalr.Method scalingMethod, Scalr.Mode resizeMode, int targetSize, BufferedImageOp... ops)Resize a given image (maintaining its original proportion) to a width and height no bigger thantargetSize(or fitting the image to the given WIDTH or HEIGHT explicitly, depending on theScalr.Modespecified) using the given scaling method and apply the givenBufferedImageOps (if any) to the result before returning it.static BufferedImageresize(BufferedImage src, Scalr.Mode resizeMode, int targetWidth, int targetHeight, BufferedImageOp... ops)Resize a given image (maintaining its original proportion) to the target width and height (or fitting the image to the given WIDTH or HEIGHT explicitly, depending on theScalr.Modespecified) and apply the givenBufferedImageOps (if any) to the result before returning it.static BufferedImageresize(BufferedImage src, Scalr.Mode resizeMode, int targetSize, BufferedImageOp... ops)Resize a given image (maintaining its original proportion) to a width and height no bigger thantargetSize(or fitting the image to the given WIDTH or HEIGHT explicitly, depending on theScalr.Modespecified) and apply the givenBufferedImageOps (if any) to the result before returning it.static BufferedImagerotate(BufferedImage src, Scalr.Rotation rotation, BufferedImageOp... ops)Used to apply aScalr.Rotationand then0or moreBufferedImageOps to a given image and return the result.protected static BufferedImagescaleImage(BufferedImage src, int targetWidth, int targetHeight, Object interpolationHintValue)Used to implement a straight-forward image-scaling operation using Java 2D.protected static BufferedImagescaleImageIncrementally(BufferedImage src, int targetWidth, int targetHeight, Scalr.Method scalingMethod, Object interpolationHintValue)Used to implement Chris Campbell's incremental-scaling algorithm: http://today.java.net/pub/a/today/2007/04/03/perils -of-image-getscaledinstance.html.
-
-
-
Field Detail
-
DEBUG_PROPERTY_NAME
public static final String DEBUG_PROPERTY_NAME
System property name used to define the debug boolean flag. Value is "imgscalr.debug".- See Also:
- Constant Field Values
-
LOG_PREFIX_PROPERTY_NAME
public static final String LOG_PREFIX_PROPERTY_NAME
System property name used to define a custom log prefix. Value is "imgscalr.logPrefix".- See Also:
- Constant Field Values
-
DEBUG
public static final boolean DEBUG
Flag used to indicate if debugging output has been enabled by setting the "imgscalr.debug" system property totrue. This value will befalseif the "imgscalr.debug" system property is undefined or set tofalse. This property can be set on startup with:
-Dimgscalr.debug=trueor by callingSystem.setProperty(String, String)to set a new property value forDEBUG_PROPERTY_NAMEbefore this class is loaded. Default value isfalse.
-
LOG_PREFIX
public static final String LOG_PREFIX
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. This property can be set on startup with:
-Dimgscalr.logPrefix=<YOUR PREFIX HERE>or by callingSystem.setProperty(String, String)to set a new property value forLOG_PREFIX_PROPERTY_NAMEbefore this class is loaded. Default value is "[imgscalr]" (including the space).
-
OP_ANTIALIAS
public static final ConvolveOp OP_ANTIALIAS
AConvolveOpusing a very light "blur" kernel that acts like an anti-aliasing filter (softens the image a bit) when applied to an image. 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 deprecatedAreaAveragingScaleFilter(which is used internally by the deprecatedImage.getScaledInstance(int, int, int)method in the JDK that imgscalr is meant to replace). This ConvolveOp uses a 3x3 kernel with the values:
For those that have worked with ConvolveOps before, this Op uses the.0f .08f .0f .08f .68f .08f .0f .08f .0f ConvolveOp.EDGE_NO_OPinstruction 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. This ConvolveOp uses noRenderingHintsvalues as internally theConvolveOpclass only uses hints when doing a color conversion between the source and destinationBufferedImagetargets. imgscalr allows theConvolveOpto create its own destination image every time, so no color conversion is ever needed and thus no hints.Performance
Use of this (and other)ConvolveOps 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, sun.awt.image.ImagingLib.Known Issues
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
-
OP_DARKER
public static final RescaleOp OP_DARKER
ARescaleOpused to make any input image 10% darker. This operation can be applied multiple times in a row if greater than 10% changes in brightness are desired.- Since:
- 4.0
-
OP_BRIGHTER
public static final RescaleOp OP_BRIGHTER
ARescaleOpused to make any input image 10% brighter. This operation can be applied multiple times in a row if greater than 10% changes in brightness are desired.- Since:
- 4.0
-
OP_GRAYSCALE
public static final ColorConvertOp OP_GRAYSCALE
AColorConvertOpused to convert any image to a grayscale color palette. Applying this op multiple times to the same image has no compounding effects.- Since:
- 4.0
-
THRESHOLD_BALANCED_SPEED
public static final int THRESHOLD_BALANCED_SPEED
Threshold (in pixels) at which point the scaling operation using theScalr.Method.AUTOMATICmethod will decide if aScalr.Method.BALANCEDmethod will be used (if smaller than or equal to threshold) or aScalr.Method.SPEEDmethod will be used (if larger than threshold). The bigger the image is being scaled to, the less noticeable degradations in the image becomes and the faster algorithms can be selected. 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 aScalr.Method.BALANCEDscale method to look decent in most all cases while using the fasterScalr.Method.SPEEDmethod for images bigger than this threshold showed no noticeable degradation over aBALANCEDscale.- See Also:
- Constant Field Values
-
THRESHOLD_QUALITY_BALANCED
public static final int THRESHOLD_QUALITY_BALANCED
Threshold (in pixels) at which point the scaling operation using theScalr.Method.AUTOMATICmethod will decide if aScalr.Method.QUALITYmethod will be used (if smaller than or equal to threshold) or aScalr.Method.BALANCEDmethod will be used (if larger than threshold). The bigger the image is being scaled to, the less noticeable degradations in the image becomes and the faster algorithms can be selected. 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 aScalr.Method.QUALITYscale method to look decent in most all cases while using the fasterScalr.Method.BALANCEDmethod for images bigger than this threshold showed no noticeable degradation over aQUALITYscale.- See Also:
- Constant Field Values
-
-
Method Detail
-
apply
public static BufferedImage apply(BufferedImage src, BufferedImageOp... ops) throws IllegalArgumentException, ImagingOpException
Used to apply, in the order given, 1 or moreBufferedImageOps to a givenBufferedImageand return the result. Feature: This implementation works around a decade-old JDK bug that can cause aRasterFormatExceptionwhen applying a perfectly validBufferedImageOps to images. Feature: This implementation also works aroundBufferedImageOps failing to apply and throwingImagingOpExceptions when run against asrcimage type that is poorly supported. Unfortunately usingImageIOand 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). It is recommended you always use this method to apply anyBufferedImageOps instead of relying on directly using theBufferedImageOp.filter(BufferedImage, BufferedImage)method. Performance: Not allBufferedImageOps are hardware accelerated operations, but many of the most popular (likeConvolveOp) 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, sun.awt.image.ImagingLib. TIP: This operation leaves the originalsrcimage unmodified. If the caller is done with thesrcimage after getting the result of this operation, remember to callImage.flush()on thesrcto free up native resources and make it easier for the GC to collect the unused image.- Parameters:
src- The image that will have the ops applied to it.ops-1or more ops to apply to the image.- Returns:
- a new
BufferedImagethat represents thesrcwith all the given operations applied to it. - Throws:
IllegalArgumentException- ifsrcisnull.IllegalArgumentException- ifopsisnullor empty.ImagingOpException- if one of the givenBufferedImageOps fails to apply. These exceptions bubble up from the inside of most of theBufferedImageOpimplementations 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 causeBufferedImageOps to fail, even when using straight forward JDK-image operations.
-
crop
public static BufferedImage crop(BufferedImage src, int width, int height, BufferedImageOp... ops) throws IllegalArgumentException, ImagingOpException
Used to crop the givensrcimage from the top-left corner and applying any optionalBufferedImageOps to the result before returning it. TIP: This operation leaves the originalsrcimage unmodified. If the caller is done with thesrcimage after getting the result of this operation, remember to callImage.flush()on thesrcto free up native resources and make it easier for the GC to collect the unused image.- Parameters:
src- The image to crop.width- The width of the bounding cropping box.height- The height of the bounding cropping box.ops-0or more ops to apply to the image. Ifnullor empty thensrcis return unmodified.- Returns:
- a new
BufferedImagerepresenting the cropped region of thesrcimage with any optional operations applied to it. - Throws:
IllegalArgumentException- ifsrcisnull.IllegalArgumentException- if any coordinates of the bounding crop box is invalid within the bounds of thesrcimage (e.g. negative or too big).ImagingOpException- if one of the givenBufferedImageOps fails to apply. These exceptions bubble up from the inside of most of theBufferedImageOpimplementations 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 causeBufferedImageOps to fail, even when using straight forward JDK-image operations.
-
crop
public static BufferedImage crop(BufferedImage src, int x, int y, int width, int height, BufferedImageOp... ops) throws IllegalArgumentException, ImagingOpException
Used to crop the givensrcimage and apply any optionalBufferedImageOps to it before returning the result. TIP: This operation leaves the originalsrcimage unmodified. If the caller is done with thesrcimage after getting the result of this operation, remember to callImage.flush()on thesrcto free up native resources and make it easier for the GC to collect the unused image.- Parameters:
src- The image to crop.x- The x-coordinate of the top-left corner of the bounding box used for cropping.y- The y-coordinate of the top-left corner of the bounding box used for cropping.width- The width of the bounding cropping box.height- The height of the bounding cropping box.ops-0or more ops to apply to the image. Ifnullor empty thensrcis return unmodified.- Returns:
- a new
BufferedImagerepresenting the cropped region of thesrcimage with any optional operations applied to it. - Throws:
IllegalArgumentException- ifsrcisnull.IllegalArgumentException- if any coordinates of the bounding crop box is invalid within the bounds of thesrcimage (e.g. negative or too big).ImagingOpException- if one of the givenBufferedImageOps fails to apply. These exceptions bubble up from the inside of most of theBufferedImageOpimplementations 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 causeBufferedImageOps to fail, even when using straight forward JDK-image operations.
-
pad
public static BufferedImage pad(BufferedImage src, int padding, BufferedImageOp... ops) throws IllegalArgumentException, ImagingOpException
Used to apply padding around the edges of an image usingColor.BLACKto fill the extra padded space and then return the result. The amount ofpaddingspecified is applied to all sides; more specifically, apaddingof2would add 2 extra pixels of space (filled by the givencolor) 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 thesrcimage. TIP: This operation leaves the originalsrcimage unmodified. If the caller is done with thesrcimage after getting the result of this operation, remember to callImage.flush()on thesrcto free up native resources and make it easier for the GC to collect the unused image.- Parameters:
src- The image the padding will be added to.padding- The number of pixels of padding to add to each side in the resulting image. If this value is0thensrcis returned unmodified.ops-0or more ops to apply to the image. Ifnullor empty thensrcis return unmodified.- Returns:
- a new
BufferedImagerepresentingsrcwith the given padding applied to it. - Throws:
IllegalArgumentException- ifsrcisnull.IllegalArgumentException- ifpaddingis <1.ImagingOpException- if one of the givenBufferedImageOps fails to apply. These exceptions bubble up from the inside of most of theBufferedImageOpimplementations 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 causeBufferedImageOps to fail, even when using straight forward JDK-image operations.
-
pad
public static BufferedImage pad(BufferedImage src, int padding, Color color, BufferedImageOp... ops) throws IllegalArgumentException, ImagingOpException
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.Colors using an alpha channel (i.e. transparency) are supported. The amount ofpaddingspecified is applied to all sides; more specifically, apaddingof2would add 2 extra pixels of space (filled by the givencolor) 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 thesrcimage. TIP: This operation leaves the originalsrcimage unmodified. If the caller is done with thesrcimage after getting the result of this operation, remember to callImage.flush()on thesrcto free up native resources and make it easier for the GC to collect the unused image.- Parameters:
src- The image the padding will be added to.padding- The number of pixels of padding to add to each side in the resulting image. If this value is0thensrcis returned unmodified.color- The color to fill the padded space with.Colors using an alpha channel (i.e. transparency) are supported.ops-0or more ops to apply to the image. Ifnullor empty thensrcis return unmodified.- Returns:
- a new
BufferedImagerepresentingsrcwith the given padding applied to it. - Throws:
IllegalArgumentException- ifsrcisnull.IllegalArgumentException- ifpaddingis <1.IllegalArgumentException- ifcolorisnull.ImagingOpException- if one of the givenBufferedImageOps fails to apply. These exceptions bubble up from the inside of most of theBufferedImageOpimplementations 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 causeBufferedImageOps to fail, even when using straight forward JDK-image operations.
-
resize
public static BufferedImage resize(BufferedImage src, int targetSize, BufferedImageOp... ops) throws IllegalArgumentException, ImagingOpException
Resize a given image (maintaining its original proportion) to a width and height no bigger thantargetSizeand apply the givenBufferedImageOps (if any) to the result before returning it. A scaling method ofScalr.Method.AUTOMATICand mode ofScalr.Mode.AUTOMATICare used. TIP: This operation leaves the originalsrcimage unmodified. If the caller is done with thesrcimage after getting the result of this operation, remember to callImage.flush()on thesrcto free up native resources and make it easier for the GC to collect the unused image.- Parameters:
src- The image that will be scaled.targetSize- The target width and height (square) that you wish the image to fit within.ops-0or more optional image operations (e.g. sharpen, blur, etc.) that can be applied to the final result before returning the image.- Returns:
- a new
BufferedImagerepresenting the scaledsrcimage. - Throws:
IllegalArgumentException- ifsrcisnull.IllegalArgumentException- iftargetSizeis < 0.ImagingOpException- if one of the givenBufferedImageOps fails to apply. These exceptions bubble up from the inside of most of theBufferedImageOpimplementations 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 causeBufferedImageOps to fail, even when using straight forward JDK-image operations.
-
resize
public static BufferedImage resize(BufferedImage src, Scalr.Method scalingMethod, int targetSize, BufferedImageOp... ops) throws IllegalArgumentException, ImagingOpException
Resize a given image (maintaining its original proportion) to a width and height no bigger thantargetSizeusing the given scaling method and apply the givenBufferedImageOps (if any) to the result before returning it. A mode ofScalr.Mode.AUTOMATICis used. TIP: This operation leaves the originalsrcimage unmodified. If the caller is done with thesrcimage after getting the result of this operation, remember to callImage.flush()on thesrcto free up native resources and make it easier for the GC to collect the unused image.- Parameters:
src- The image that will be scaled.scalingMethod- The method used for scaling the image; preferring speed to quality or a balance of both.targetSize- The target width and height (square) that you wish the image to fit within.ops-0or more optional image operations (e.g. sharpen, blur, etc.) that can be applied to the final result before returning the image.- Returns:
- a new
BufferedImagerepresenting the scaledsrcimage. - Throws:
IllegalArgumentException- ifsrcisnull.IllegalArgumentException- ifscalingMethodisnull.IllegalArgumentException- iftargetSizeis < 0.ImagingOpException- if one of the givenBufferedImageOps fails to apply. These exceptions bubble up from the inside of most of theBufferedImageOpimplementations 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 causeBufferedImageOps to fail, even when using straight forward JDK-image operations.- See Also:
Scalr.Method
-
resize
public static BufferedImage resize(BufferedImage src, Scalr.Mode resizeMode, int targetSize, BufferedImageOp... ops) throws IllegalArgumentException, ImagingOpException
Resize a given image (maintaining its original proportion) to a width and height no bigger thantargetSize(or fitting the image to the given WIDTH or HEIGHT explicitly, depending on theScalr.Modespecified) and apply the givenBufferedImageOps (if any) to the result before returning it. A scaling method ofScalr.Method.AUTOMATICis used. TIP: This operation leaves the originalsrcimage unmodified. If the caller is done with thesrcimage after getting the result of this operation, remember to callImage.flush()on thesrcto free up native resources and make it easier for the GC to collect the unused image.- Parameters:
src- The image that will be scaled.resizeMode- Used to indicate how imgscalr should calculate the final target size for the image, either fitting the image to the given width (Scalr.Mode.FIT_TO_WIDTH) or fitting the image to the given height (Scalr.Mode.FIT_TO_HEIGHT). IfScalr.Mode.AUTOMATICis passed in, imgscalr will calculate proportional dimensions for the scaled image based on its orientation (landscape, square or portrait). Unless you have very specific size requirements, most of the time you just want to useScalr.Mode.AUTOMATICto "do the right thing".targetSize- The target width and height (square) that you wish the image to fit within.ops-0or more optional image operations (e.g. sharpen, blur, etc.) that can be applied to the final result before returning the image.- Returns:
- a new
BufferedImagerepresenting the scaledsrcimage. - Throws:
IllegalArgumentException- ifsrcisnull.IllegalArgumentException- ifresizeModeisnull.IllegalArgumentException- iftargetSizeis < 0.ImagingOpException- if one of the givenBufferedImageOps fails to apply. These exceptions bubble up from the inside of most of theBufferedImageOpimplementations 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 causeBufferedImageOps to fail, even when using straight forward JDK-image operations.- See Also:
Scalr.Mode
-
resize
public static BufferedImage resize(BufferedImage src, Scalr.Method scalingMethod, Scalr.Mode resizeMode, int targetSize, BufferedImageOp... ops) throws IllegalArgumentException, ImagingOpException
Resize a given image (maintaining its original proportion) to a width and height no bigger thantargetSize(or fitting the image to the given WIDTH or HEIGHT explicitly, depending on theScalr.Modespecified) using the given scaling method and apply the givenBufferedImageOps (if any) to the result before returning it. TIP: This operation leaves the originalsrcimage unmodified. If the caller is done with thesrcimage after getting the result of this operation, remember to callImage.flush()on thesrcto free up native resources and make it easier for the GC to collect the unused image.- Parameters:
src- The image that will be scaled.scalingMethod- The method used for scaling the image; preferring speed to quality or a balance of both.resizeMode- Used to indicate how imgscalr should calculate the final target size for the image, either fitting the image to the given width (Scalr.Mode.FIT_TO_WIDTH) or fitting the image to the given height (Scalr.Mode.FIT_TO_HEIGHT). IfScalr.Mode.AUTOMATICis passed in, imgscalr will calculate proportional dimensions for the scaled image based on its orientation (landscape, square or portrait). Unless you have very specific size requirements, most of the time you just want to useScalr.Mode.AUTOMATICto "do the right thing".targetSize- The target width and height (square) that you wish the image to fit within.ops-0or more optional image operations (e.g. sharpen, blur, etc.) that can be applied to the final result before returning the image.- Returns:
- a new
BufferedImagerepresenting the scaledsrcimage. - Throws:
IllegalArgumentException- ifsrcisnull.IllegalArgumentException- ifscalingMethodisnull.IllegalArgumentException- ifresizeModeisnull.IllegalArgumentException- iftargetSizeis < 0.ImagingOpException- if one of the givenBufferedImageOps fails to apply. These exceptions bubble up from the inside of most of theBufferedImageOpimplementations 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 causeBufferedImageOps to fail, even when using straight forward JDK-image operations.- See Also:
Scalr.Method,Scalr.Mode
-
resize
public static BufferedImage resize(BufferedImage src, int targetWidth, int targetHeight, BufferedImageOp... ops) throws IllegalArgumentException, ImagingOpException
Resize a given image (maintaining its original proportion) to the target width and height and apply the givenBufferedImageOps (if any) to the result before returning it. A scaling method ofScalr.Method.AUTOMATICand mode ofScalr.Mode.AUTOMATICare used. TIP: See the class description to understand how this class handles recalculation of thetargetWidthortargetHeightdepending on the image's orientation in order to maintain the original proportion. TIP: This operation leaves the originalsrcimage unmodified. If the caller is done with thesrcimage after getting the result of this operation, remember to callImage.flush()on thesrcto free up native resources and make it easier for the GC to collect the unused image.- Parameters:
src- The image that will be scaled.targetWidth- The target width that you wish the image to have.targetHeight- The target height that you wish the image to have.ops-0or more optional image operations (e.g. sharpen, blur, etc.) that can be applied to the final result before returning the image.- Returns:
- a new
BufferedImagerepresenting the scaledsrcimage. - Throws:
IllegalArgumentException- ifsrcisnull.IllegalArgumentException- iftargetWidthis < 0 or iftargetHeightis < 0.ImagingOpException- if one of the givenBufferedImageOps fails to apply. These exceptions bubble up from the inside of most of theBufferedImageOpimplementations 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 causeBufferedImageOps to fail, even when using straight forward JDK-image operations.
-
resize
public static BufferedImage resize(BufferedImage src, Scalr.Method scalingMethod, int targetWidth, int targetHeight, BufferedImageOp... ops)
Resize a given image (maintaining its original proportion) to the target width and height using the given scaling method and apply the givenBufferedImageOps (if any) to the result before returning it. A mode ofScalr.Mode.AUTOMATICis used. TIP: See the class description to understand how this class handles recalculation of thetargetWidthortargetHeightdepending on the image's orientation in order to maintain the original proportion. TIP: This operation leaves the originalsrcimage unmodified. If the caller is done with thesrcimage after getting the result of this operation, remember to callImage.flush()on thesrcto free up native resources and make it easier for the GC to collect the unused image.- Parameters:
src- The image that will be scaled.scalingMethod- The method used for scaling the image; preferring speed to quality or a balance of both.targetWidth- The target width that you wish the image to have.targetHeight- The target height that you wish the image to have.ops-0or more optional image operations (e.g. sharpen, blur, etc.) that can be applied to the final result before returning the image.- Returns:
- a new
BufferedImagerepresenting the scaledsrcimage. - Throws:
IllegalArgumentException- ifsrcisnull.IllegalArgumentException- ifscalingMethodisnull.IllegalArgumentException- iftargetWidthis < 0 or iftargetHeightis < 0.ImagingOpException- if one of the givenBufferedImageOps fails to apply. These exceptions bubble up from the inside of most of theBufferedImageOpimplementations 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 causeBufferedImageOps to fail, even when using straight forward JDK-image operations.- See Also:
Scalr.Method
-
resize
public static BufferedImage resize(BufferedImage src, Scalr.Mode resizeMode, int targetWidth, int targetHeight, BufferedImageOp... ops) throws IllegalArgumentException, ImagingOpException
Resize a given image (maintaining its original proportion) to the target width and height (or fitting the image to the given WIDTH or HEIGHT explicitly, depending on theScalr.Modespecified) and apply the givenBufferedImageOps (if any) to the result before returning it. A scaling method ofScalr.Method.AUTOMATICis used. TIP: See the class description to understand how this class handles recalculation of thetargetWidthortargetHeightdepending on the image's orientation in order to maintain the original proportion. TIP: This operation leaves the originalsrcimage unmodified. If the caller is done with thesrcimage after getting the result of this operation, remember to callImage.flush()on thesrcto free up native resources and make it easier for the GC to collect the unused image.- Parameters:
src- The image that will be scaled.resizeMode- Used to indicate how imgscalr should calculate the final target size for the image, either fitting the image to the given width (Scalr.Mode.FIT_TO_WIDTH) or fitting the image to the given height (Scalr.Mode.FIT_TO_HEIGHT). IfScalr.Mode.AUTOMATICis passed in, imgscalr will calculate proportional dimensions for the scaled image based on its orientation (landscape, square or portrait). Unless you have very specific size requirements, most of the time you just want to useScalr.Mode.AUTOMATICto "do the right thing".targetWidth- The target width that you wish the image to have.targetHeight- The target height that you wish the image to have.ops-0or more optional image operations (e.g. sharpen, blur, etc.) that can be applied to the final result before returning the image.- Returns:
- a new
BufferedImagerepresenting the scaledsrcimage. - Throws:
IllegalArgumentException- ifsrcisnull.IllegalArgumentException- ifresizeModeisnull.IllegalArgumentException- iftargetWidthis < 0 or iftargetHeightis < 0.ImagingOpException- if one of the givenBufferedImageOps fails to apply. These exceptions bubble up from the inside of most of theBufferedImageOpimplementations 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 causeBufferedImageOps to fail, even when using straight forward JDK-image operations.- See Also:
Scalr.Mode
-
resize
public static BufferedImage resize(BufferedImage src, Scalr.Method scalingMethod, Scalr.Mode resizeMode, int targetWidth, int targetHeight, BufferedImageOp... ops) throws IllegalArgumentException, ImagingOpException
Resize a given image (maintaining its original proportion) to the target width and height (or fitting the image to the given WIDTH or HEIGHT explicitly, depending on theScalr.Modespecified) using the given scaling method and apply the givenBufferedImageOps (if any) to the result before returning it. TIP: See the class description to understand how this class handles recalculation of thetargetWidthortargetHeightdepending on the image's orientation in order to maintain the original proportion. TIP: This operation leaves the originalsrcimage unmodified. If the caller is done with thesrcimage after getting the result of this operation, remember to callImage.flush()on thesrcto free up native resources and make it easier for the GC to collect the unused image.- Parameters:
src- The image that will be scaled.scalingMethod- The method used for scaling the image; preferring speed to quality or a balance of both.resizeMode- Used to indicate how imgscalr should calculate the final target size for the image, either fitting the image to the given width (Scalr.Mode.FIT_TO_WIDTH) or fitting the image to the given height (Scalr.Mode.FIT_TO_HEIGHT). IfScalr.Mode.AUTOMATICis passed in, imgscalr will calculate proportional dimensions for the scaled image based on its orientation (landscape, square or portrait). Unless you have very specific size requirements, most of the time you just want to useScalr.Mode.AUTOMATICto "do the right thing".targetWidth- The target width that you wish the image to have.targetHeight- The target height that you wish the image to have.ops-0or more optional image operations (e.g. sharpen, blur, etc.) that can be applied to the final result before returning the image.- Returns:
- a new
BufferedImagerepresenting the scaledsrcimage. - Throws:
IllegalArgumentException- ifsrcisnull.IllegalArgumentException- ifscalingMethodisnull.IllegalArgumentException- ifresizeModeisnull.IllegalArgumentException- iftargetWidthis < 0 or iftargetHeightis < 0.ImagingOpException- if one of the givenBufferedImageOps fails to apply. These exceptions bubble up from the inside of most of theBufferedImageOpimplementations 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 causeBufferedImageOps to fail, even when using straight forward JDK-image operations.- See Also:
Scalr.Method,Scalr.Mode
-
rotate
public static BufferedImage rotate(BufferedImage src, Scalr.Rotation rotation, BufferedImageOp... ops) throws IllegalArgumentException, ImagingOpException
Used to apply aScalr.Rotationand then0or moreBufferedImageOps to a given image and return the result. TIP: This operation leaves the originalsrcimage unmodified. If the caller is done with thesrcimage after getting the result of this operation, remember to callImage.flush()on thesrcto free up native resources and make it easier for the GC to collect the unused image.- Parameters:
src- The image that will have the rotation applied to it.rotation- The rotation that will be applied to the image.ops- Zero or more optional image operations (e.g. sharpen, blur, etc.) that can be applied to the final result before returning the image.- Returns:
- a new
BufferedImagerepresentingsrcrotated by the given amount and any optional ops applied to it. - Throws:
IllegalArgumentException- ifsrcisnull.IllegalArgumentException- ifrotationisnull.ImagingOpException- if one of the givenBufferedImageOps fails to apply. These exceptions bubble up from the inside of most of theBufferedImageOpimplementations 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 causeBufferedImageOps to fail, even when using straight forward JDK-image operations.- See Also:
Scalr.Rotation
-
log
protected static void log(int depth, String message, Object... params)Used to write out a useful and well-formatted log message by any piece of code inside of the imgscalr library. If a message cannot be logged (logging is disabled) then this method returns immediately. NOTE: Because Java will auto-box primitive arguments into Objects when building out theparamsarray, care should be taken not to call this method with primitive values unlessDEBUGistrue; otherwise the VM will be spending time performing unnecessary auto-boxing calculations.- Parameters:
depth- The indentation level of the log message.message- The log message in format string syntax that will be logged.params- The parameters that will be swapped into all the place holders in the original messages before being logged.- See Also:
LOG_PREFIX,LOG_PREFIX_PROPERTY_NAME
-
createOptimalImage
protected static BufferedImage createOptimalImage(BufferedImage src)
Used to create aBufferedImagewith the most optimal RGB TYPE (BufferedImage.TYPE_INT_RGBorBufferedImage.TYPE_INT_ARGB) capable of being rendered into from the givensrc. The width and height of both images will be identical. This does not perform a copy of the image data fromsrcinto the result image; seecopyToOptimalImage(BufferedImage)for that. We force all rendering results into one of these two types, avoiding the case where a source image is of an unsupported (or poorly supported) format by Java2D causing the rendering result to end up looking terrible (common with GIFs) or be totally corrupt (e.g. solid black image). Originally reported by Magnus Kvalheim from Movellas when scaling certain GIF and PNG images.- Parameters:
src- The source image that will be analyzed to determine the most optimal image type it can be rendered into.- Returns:
- a new
BufferedImagerepresenting the most optimal target image type thatsrccan be rendered into. - See Also:
- How Java2D handles poorly supported image types, Thanks to Morten Nobel for implementation hint
-
createOptimalImage
protected static BufferedImage createOptimalImage(BufferedImage src, int width, int height) throws IllegalArgumentException
Used to create aBufferedImagewith the given dimensions and the most optimal RGB TYPE (BufferedImage.TYPE_INT_RGBorBufferedImage.TYPE_INT_ARGB) capable of being rendered into from the givensrc. This does not perform a copy of the image data fromsrcinto the result image; seecopyToOptimalImage(BufferedImage)for that. We force all rendering results into one of these two types, avoiding the case where a source image is of an unsupported (or poorly supported) format by Java2D causing the rendering result to end up looking terrible (common with GIFs) or be totally corrupt (e.g. solid black image). Originally reported by Magnus Kvalheim from Movellas when scaling certain GIF and PNG images.- Parameters:
src- The source image that will be analyzed to determine the most optimal image type it can be rendered into.width- The width of the newly created resulting image.height- The height of the newly created resulting image.- Returns:
- a new
BufferedImagerepresenting the most optimal target image type thatsrccan be rendered into. - Throws:
IllegalArgumentException- ifwidthorheightare < 0.- See Also:
- How Java2D handles poorly supported image types, Thanks to Morten Nobel for implementation hint
-
copyToOptimalImage
protected static BufferedImage copyToOptimalImage(BufferedImage src) throws IllegalArgumentException
Used to copy aBufferedImagefrom a non-optimal type into a newBufferedImageinstance of an optimal type (RGB or ARGB). Ifsrcis already of an optimal type, then it is returned unmodified. This method is meant to be used by any calling code (imgscalr's or otherwise) to convert any inbound image from a poorly supported image type into the 2 most well-supported image types in Java2D (BufferedImage.TYPE_INT_RGBorBufferedImage.TYPE_INT_ARGB) in order to ensure all subsequent graphics operations are performed as efficiently and correctly as possible. When using Java2D to work with image types that are not well supported, the results can be anything from exceptions bubbling up from the depths of Java2D to images being completely corrupted and just returned as solid black.- Parameters:
src- The image to copy (if necessary) into an optimally typedBufferedImage.- Returns:
- a representation of the
srcimage in an optimally typedBufferedImage, otherwisesrcif it was already of an optimal type. - Throws:
IllegalArgumentException- ifsrcisnull.
-
determineScalingMethod
protected static Scalr.Method determineScalingMethod(int targetWidth, int targetHeight, float ratio)
Used to determine the scalingScalr.Methodthat is best suited for scaling the image to the targeted dimensions. This method is intended to be used to select a specific scalingScalr.Methodwhen aScalr.Method.AUTOMATICmethod is specified. This method utilizes theTHRESHOLD_QUALITY_BALANCEDandTHRESHOLD_BALANCED_SPEEDthresholds when selecting which method should be used by comparing the primary dimension (width or height) against the threshold and seeing where the image falls. The primary dimension is determined by looking at the orientation of the image: landscape or square images use their width and portrait-oriented images use their height.- Parameters:
targetWidth- The target width for the scaled image.targetHeight- The target height for the scaled image.ratio- A height/width ratio used to determine the orientation of the image so the primary dimension (width or height) can be selected to test if it is greater than or less than a particular threshold.- Returns:
- the fastest
Scalr.Methodsuited for scaling the image to the specified dimensions while maintaining a good-looking result.
-
scaleImage
protected static BufferedImage scaleImage(BufferedImage src, int targetWidth, int targetHeight, Object interpolationHintValue)
Used to implement a straight-forward image-scaling operation using Java 2D. This method uses the Oracle-encouraged method ofGraphics2D.drawImage(...)to scale the given image with the given interpolation hint.- Parameters:
src- The image that will be scaled.targetWidth- The target width for the scaled image.targetHeight- The target height for the scaled image.interpolationHintValue- TheRenderingHintsinterpolation value used to indicate the method thatGraphics2Dshould use when scaling the image.- Returns:
- the result of scaling the original
srcto the given dimensions using the given interpolation method.
-
scaleImageIncrementally
protected static BufferedImage scaleImageIncrementally(BufferedImage src, int targetWidth, int targetHeight, Scalr.Method scalingMethod, Object interpolationHintValue)
Used to implement Chris Campbell's incremental-scaling algorithm: http://today.java.net/pub/a/today/2007/04/03/perils -of-image-getscaledinstance.html. Modifications to the original algorithm are variable names and comments added for clarity and the hard-coding of using BICUBIC interpolation as well as the explicit "flush()" operation on the interim BufferedImage instances to avoid resource leaking.- Parameters:
src- The image that will be scaled.targetWidth- The target width for the scaled image.targetHeight- The target height for the scaled image.scalingMethod- The scaling method specified by the user (or calculated by imgscalr) to use for this incremental scaling operation.interpolationHintValue- TheRenderingHintsinterpolation value used to indicate the method thatGraphics2Dshould use when scaling the image.- Returns:
- an image scaled to the given dimensions using the given rendering hint.
-
-