Class ImageUtil

java.lang.Object
ca.corbett.extras.image.ImageUtil

public class ImageUtil extends Object
Contains generic methods for dealing with images and image data.
Since:
2012-09-01
Author:
scorbo2
  • Field Details

    • COMPRESSION_QUALITY

      protected static final float COMPRESSION_QUALITY
      JPEG compression quality to use. *
      See Also:
  • Constructor Details

    • ImageUtil

      protected ImageUtil()
      Protected constructor to allow subclassing for application-specific utility methods while preventing direct instantiation of this utility class.
  • Method Details

    • createImageWriter

      protected static void createImageWriter()
      Internal method to create our internal image utilities.
    • loadImageIcon

      public static ImageIcon loadImageIcon(File file) throws IOException
      Loads and returns an ImageIcon from the specified image file. Generally, you should use loadImage() instead, as that returns a BufferedImage that can be manipulated in memory and then written out using saveImage(), but certain types of images (namely animated GIFs) are better in ImageIcon format. ImagePanel has native support for animated GIF images, but you must supply them as ImageIcon instances and not BufferedImage instances.
      Parameters:
      file - The File from which to load the image icon.
      Returns:
      an ImageIcon instance.
      Throws:
      IOException - If the image could not be loaded.
    • loadImageIcon

      public static ImageIcon loadImageIcon(URL url) throws IOException
      Loads and returns an ImageIcon from the specified URL. Generally, you should use loadImage() instead, as that returns a BufferedImage that can be manipulated in memory and then written out using saveImage(), but certain types of images (namely animated GIFs) are better in ImageIcon format. ImagePanel has native support for animated GIF images, but you must supply them as ImageIcon instances and not BufferedImage instances.
      Parameters:
      url - The URL from which to load the image icon.
      Returns:
      an ImageIcon instance.
      Throws:
      IOException - If the image could not be loaded.
    • validateImageIcon

      protected static ImageIcon validateImageIcon(ImageIcon image) throws IOException
      Invoked internally to attempt to validate the results of loading an ImageIcon. It seems that ImageIcon's constructor will not throw any kind of exception if the load fails, leaving callers with no obvious sign of trouble. The returned ImageIcon in that case would be non-null, but would not contain any valid image data. This extra validation step intercepts the ImageIcon before we return it, and adds an IOException if the image appears to be invalid.
      Parameters:
      image - A candidate ImageIcon to evaluate.
      Returns:
      The input ImageIcon if it appears valid.
      Throws:
      IOException - If the image appears to be invalid.
    • loadImage

      public static BufferedImage loadImage(URL url) throws IOException
      Loads a BufferedImage from the specified URL.
      Parameters:
      url - The URL of the image to load.
      Returns:
      The BufferedImage contained in that URL.
      Throws:
      IOException - If the image could not be loaded.
    • loadImage

      public static BufferedImage loadImage(File file) throws IOException
      Loads a BufferedImage from the specified file.
      Parameters:
      file - The file in question. Can be any format supported by javax.imageio.ImageIO.
      Returns:
      A BufferedImage containing the image data.
      Throws:
      IOException - If the image could not be loaded.
    • loadImage

      public static BufferedImage loadImage(InputStream inStream) throws IOException
      Loads a BufferedImage from the specified input stream.
      Parameters:
      inStream - The input stream in question. Must contain an image in a format supported by javax.imageio.ImageIo.
      Returns:
      A BufferedImage containing the image data.
      Throws:
      IOException - If the image could not be loaded.
    • loadFromResource

      public static BufferedImage loadFromResource(Class<?> loadingClass, String resourceName) throws IOException
      Attempts to load the given resource for the given class.
      Parameters:
      loadingClass - The class to be used for loading the resource.
      resourceName - The fully qualified name of the resource to load. Must be a supported image format.
      Returns:
      The image.
      Throws:
      IOException - If the image could not be loaded.
    • loadFromResource

      public static BufferedImage loadFromResource(Class<?> loadingClass, String resourceName, int width, int height) throws IOException
      Attempts to load the given resource as an image, and also scales it to the given dimensions. The image scale will be done with transparency. Scaling is skipped if the image dimensions match the given dimensions.
      Parameters:
      loadingClass - The class to be used for loading the resource.
      resourceName - The fully qualified name of the resource to load. Must be a supported image format.
      width - The desired width of the image.
      height - The desired height of the image.
      Returns:
      The requested image.
      Throws:
      IOException - If the image could not be loaded.
    • saveImage

      public static void saveImage(BufferedImage image, File file) throws IOException
      Saves the specified BufferedImage to the specified file. The default save format is jpeg at 95% quality. Use the other saveImage() methods to specify a different save format or compression quality.
      Parameters:
      image - The BufferedImage to save
      file - The File to which to save.
      Throws:
      IOException - If the image could not be saved.
    • saveImage

      public static void saveImage(BufferedImage image, File file, float compressionQuality) throws IOException
      Saves the specified BufferedImage to the specified file in jpeg format with the specified compression quality.
      Parameters:
      image - The BufferedImage to save.
      file - The File to which to save.
      compressionQuality - The jpeg compression quality value to use.
      Throws:
      IOException - If the image could not be saved.
    • saveImage

      public static void saveImage(BufferedImage image, File file, ImageWriteParam writeParam) throws IOException
      Saves the specified BufferedImage to the specified file in jpeg format with the specified ImageWriteParam. You can use this to specify your own image write parameters. If you only want to set the jpeg compression quality, use saveImage(BufferedImage,File,float) instead.
      Parameters:
      image - The BufferedImage to save.
      file - The File to which to save.
      writeParam - The ImageWriteParam to use.
      Throws:
      IOException - If the image could not be saved.
    • saveImage

      public static void saveImage(BufferedImage image, File file, ImageWriter writer, ImageWriteParam writeParam) throws IOException
      Saves the specified BufferedImage using the specified ImageWriter and ImageWriteParam. This allows you to save in some format other than jpeg. For example: ImageIO.getImageWritersByFormatName("png")
      Parameters:
      image - The BufferedImage to save.
      file - The File to which to save.
      writer - The ImageWriter to use.
      writeParam - The ImageWriteParam to use.
      Throws:
      IOException - If the image could not be saved.
    • serializeImage

      public static byte[] serializeImage(BufferedImage image) throws IOException
      Converts the given image to a byte array, which can then be serialized. Default format is jpeg at 95% compression quality. Use the overloaded serializeImage() methods to specify a different format or compression quality.
      Parameters:
      image - The BufferedImage to serialize
      Returns:
      a byte array representing the image in question.
      Throws:
      IOException - if an error occurs during image serialization.
    • serializeImage

      public static byte[] serializeImage(BufferedImage image, float compressionQuality) throws IOException
      Converts the given image to a byte array, which can then be serialized. The image will be serialized in jpeg format with the specified compression quality. For more control over the output, or to change the output format, use the overloaded serializeImage methods instead.
      Parameters:
      image - The BufferedImage to serialize.
      compressionQuality - The jpeg compression quality to use.
      Returns:
      A byte array representing the image in question.
      Throws:
      IOException - if an error occurs during serialization.
    • serializeImage

      public static byte[] serializeImage(BufferedImage image, ImageWriteParam writeParam) throws IOException
      Converts the given image to a byte array, which can then be serialized. The image will be serialized in jpeg format with the given ImageWriteParam. Use the ImageWriteParam to control various aspects of the image generation. If you just want to set the jpeg compression level, use serializeImage(BufferedImage, float) instead.
      Parameters:
      image - The BufferedImage to serialize.
      writeParam - The ImageWriteParam to use when generating the output image.
      Returns:
      A byte array representing the image in question.
      Throws:
      IOException - If an error occurs during serialization.
    • serializeImage

      public static byte[] serializeImage(BufferedImage image, ImageWriter writer, ImageWriteParam writeParam) throws IOException
      Converts the given image to a byte array, which can then be serialized. Use the ImageWriter and ImageWriteParam parameters to control the output format of the generated image if you don't like the default jpeg. For example: ImageIO.getImageWritersByFormatName("png")
      Parameters:
      image - The BufferedImage to save.
      writer - The ImageWriter to use.
      writeParam - The ImageWriteParam to use.
      Returns:
      A byte array representing the image in question.
      Throws:
      IOException - If an error occurs during serialization.
    • deserializeImage

      public static BufferedImage deserializeImage(byte[] arr) throws IOException
      Converts the given byte array (created via serializeImage) back into a BufferedImage.
      Parameters:
      arr - A byte array generated by one of the serializeImage methods.
      Returns:
      A BufferedImage representing the image data, or null if the input array was null.
      Throws:
      IOException - If an error occurs during deserialization.
    • generateThumbnail

      public static BufferedImage generateThumbnail(File image, int width, int height) throws IOException
      Generates an image thumbnail for the given image file using the given dimensions. Note that the image will be resized proportionally so that it fits inside the max of the specified width and height. For example, an 800x600 image will be shrunk to 150x112.
      Parameters:
      image - The image file in question. Can be any format supported by javax.imageio.ImageIO.
      width - The desired max width of the thumbnail.
      height - The desired max height of the thumbnail.
      Returns:
      A BufferedImage containing the thumbnail.
      Throws:
      IOException - on input/output error.
    • scaleIcon

      public static ImageIcon scaleIcon(ImageIcon imageIcon, int size)
      Returns a scaled version of the input icon, if it is not already at the given size (assuming square icons). If the input icon is null, null is returned.
      Parameters:
      imageIcon - Any ImageIcon instance that contains a BufferedImage.
      size - The requested size (assuming square icons).
      Returns:
      A scaled ImageIcon instance, or null if the input icon was null or did not contain a BufferedImage.
    • generateThumbnail

      public static BufferedImage generateThumbnail(BufferedImage sourceImage, int width, int height)
      Generates an image thumbnail for the given image using the given dimensions. The image will be resized proportionally to fit into the specified width and height.
      Parameters:
      sourceImage - The image in question
      width - The desired max width of the thumbnail
      height - The desired max height of the thumbnail
      Returns:
      A BufferedImage representing the thumbnail
    • generateThumbnailWithTransparency

      public static BufferedImage generateThumbnailWithTransparency(File image, int width, int height) throws IOException
      Generates an image thumbnail for the given image file using the given dimensions. The resulting BufferedImage will be rendered with an alpha channel to preserve transparency. Note that the image will be resized proportionally so that it fits inside the max of the specified width and height. For example, an 800x600 image will be shrunk to 150x112.
      Parameters:
      image - The image file in question. Can be any format supported by javax.imageio.ImageIO.
      width - The desired max width of the thumbnail.
      height - The desired max height of the thumbnail.
      Returns:
      A BufferedImage containing the thumbnail.
      Throws:
      IOException - on input/output error.
    • generateThumbnailWithTransparency

      public static BufferedImage generateThumbnailWithTransparency(BufferedImage sourceImage, int width, int height)
      Generates an image thumbnail for the given image using the given dimensions. The resulting BufferedImage will be rendered with an alpha channel to preserve transparency. The image will be resized proportionally to fit into the specified width and height.
      Parameters:
      sourceImage - The image in question
      width - The desired max width of the thumbnail
      height - The desired max height of the thumbnail
      Returns:
      A BufferedImage representing the thumbnail
    • getImageDimensions

      public static Dimension getImageDimensions(File imageFile) throws IOException
      Very quickly reads the dimensions of the given image without parsing the entire image data. This is useful for displaying basic information about an image without paying the computational expense of actually loading the whole thing.
      Parameters:
      imageFile - The image file in question. Must be in an image format supported by ImageIO.
      Returns:
      The dimensions of the image.
      Throws:
      IOException - for unsupported image formats, or if the file is corrupt or missing.
    • getAspectRatioDescription

      public static String getAspectRatioDescription(Dimension imageDim)
      Returns a human-readable description of an image's aspect ratio based on the given dimensions. The possible return values are "portrait", "square", or "landscape" based on the ratio of width versus height. A "fuzzy" percentage is applied, such that images don't need to be exactly square to be considered "square". For example, an image of 999x1000 is technically portrait, but really, it could be considered "close enough" to be called square.
    • scaleImageToFitSquareBounds

      public static BufferedImage scaleImageToFitSquareBounds(BufferedImage image, int maxDimension)
      Scales an image up or down proportionally until it fits inside the square bounding area specified by maxDimension. The image is scaled based on its largest dimension. For example, a landscape image will be scaled so that its with matches maxDimension. A portrait image will be scaled so that its height matches maxDimension. A square image will be scaled until both width and height equals maxDimension.

      Note: this method will return an image that is not square, if the input image is not square. You can use scaleImageToFitSquareBounds(BufferedImage,int,boolean) to force the resulting image to be square.

      Parameters:
      image - The image to scale.
      maxDimension - The desired largest dimension of the scaled image.
      Returns:
      The scaled image.
    • scaleImageToFitSquareBounds

      public static BufferedImage scaleImageToFitSquareBounds(BufferedImage image, int maxDimension, boolean makeSquare)
      Scales an image up or down proportionally until it fits inside the square bounding area specified by maxDimension. The image is scaled based on its largest dimension. For example, a landscape image will be scaled so that its with matches maxDimension. A portrait image will be scaled so that its height matches maxDimension. A square image will be scaled until both width and height equals maxDimension.

      Note: If the makeSquare parameter is true, the resulting image will be expanded as needed (with transparency) so that the returned image is centered within a perfectly square image. If your image is portrait, for example, there will be horizontal transparent padding added to the left and right such that the returned image's width and height are equal, but without distorting the image itself.

      Parameters:
      image - The image to scale.
      maxDimension - The desired largest dimension of the scaled image.
      makeSquare - If true, will apply transparent padding if needed so the returned image is square.
      Returns:
      The scaled image.
    • isImageFile

      public static boolean isImageFile(File f)
      Very quick and cheesy way of determining if a file is of a supported image type.
    • savePngImage

      public static void savePngImage(BufferedImage image, File file) throws IOException
      Saves the specified BufferedImage to the specified file in PNG format. PNG is a lossless format that supports transparency, making it ideal for graphics, screenshots, and images that require an alpha channel.
      Parameters:
      image - The BufferedImage to save.
      file - The File to which to save.
      Throws:
      IOException - If the image could not be saved or if no PNG writer is available.