Advertisement
igede

Untitled

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