RickyS20_

Untitled

Nov 23rd, 2020
167
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.00 KB | None | 0 0
  1.  
  2. /**
  3.  * ImageFileManager is a small utility class with static methods to load
  4.  * and save images.
  5.  *
  6.  * The files on disk can be in JPG or PNG image format. For files written
  7.  * by this class, the format is determined by the constant IMAGE_FORMAT.
  8.  *
  9.  * @author (Ricky S)
  10.  * @version (1.0)
  11.  */
  12.  
  13. import java.awt.image.*;
  14. import javax.imageio.*;
  15. import java.io.*;
  16.  
  17. public class ImageFileManager
  18. {
  19.     // A constant for the image format that this writer uses for writing.
  20.     // Available formats are "jpg" and "png".
  21.     private static final String IMAGE_FORMAT = "jpg";
  22.  
  23.     /**
  24.       * Read an image file from disk and return it as an image. This method
  25.       * can read JPG and PNG file formats. In case of any problem (e.g the file
  26.       * does not exist, is in an undecodable format, or any other read error)
  27.       * this method returns null.
  28.       *
  29.       * @param imageFile The image file to be loaded.
  30.       * @return The image object or null is it could not be read.
  31.       */
  32.      public static OFImage loadImage(File imageFile)
  33.      {
  34.          try {
  35.              BufferedImage image = ImageIO.read(imageFile);
  36.              if(image == null || (image.getWidth(null) < 0)) {
  37.                  // we could not load the image - probably invalid file format
  38.                  return null;
  39.                 }
  40.                 return new OFImage(image);
  41.             }
  42.             catch(IOException exc) {
  43.                 return null;
  44.             }
  45.         }
  46.         /**
  47.           * Write an image file to disk. The file format is JPG. In case of any
  48.           * problem the method just silently returns.
  49.           *
  50.           * @param image The image to be saved.
  51.           * @param file The file to save to.
  52.           */
  53.          public static void saveImage(OFImage image, File file)
  54.          {
  55.              try {
  56.                  ImageIO.write(image, IMAGE_FORMAT, file);
  57.                 }
  58.                 catch(IOException exc) {
  59.                     return;
  60.                 }
  61.             }
  62. }
Advertisement
Add Comment
Please, Sign In to add comment