Advertisement
mnaufaldillah

ImageFileManager Tugas 7

Dec 6th, 2020
259
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.02 KB | None | 0 0
  1. import java.awt.image.*;
  2. import javax.imageio.*;
  3. import java.io.*;
  4. import java.awt.image.*;
  5. import javax.imageio.*;
  6. import java.io.*;
  7. /**
  8.  * ImageFileManager is a small utility class with static methods to load
  9.  * and save images.
  10.  *
  11.  * The files on disk can be in JPG or PNG image format. For files written
  12.  * by this class, the format is determined by the constant IMAGE_FORMAT.
  13.  *
  14.  * @author Muhammad Naufaldillah
  15.  * @version 5 December 2020
  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.         {
  36.             BufferedImage image = ImageIO.read(imageFile);
  37.             if(image == null || (image.getWidth(null) < 0))
  38.             {
  39.                 // we could not load the image - probably invalid file format
  40.                 return null;
  41.             }
  42.             return new OFImage(image);
  43.         }
  44.         catch(IOException exc)
  45.         {
  46.             return null;
  47.         }
  48.     }
  49.    
  50.     /**
  51.      * Write an image file to disk. The file format is JPG. In case of any
  52.      * problem the method just silently returns.
  53.      *
  54.      * @param image The image to be saved.
  55.      * @param file The file to save to.
  56.      */
  57.     public static void saveImage(OFImage image, File file)
  58.     {
  59.         try
  60.         {
  61.             ImageIO.write(image, IMAGE_FORMAT, file);
  62.         }
  63.         catch(IOException exc)
  64.         {
  65.             return;
  66.         }
  67.     }
  68. }
  69.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement