nizayulia

image file manager

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