From 7e11b5a58a9f34049a5078139446ca080ff9b50b Mon Sep 17 00:00:00 2001 From: Timothée Floure Date: Mon, 2 May 2016 13:52:00 +0200 Subject: Implement client.ImageCollection --- src/ch/epfl/xblast/client/ImageCollection.java | 91 ++++++++++++++++++++++++++ 1 file changed, 91 insertions(+) create mode 100644 src/ch/epfl/xblast/client/ImageCollection.java (limited to 'src') diff --git a/src/ch/epfl/xblast/client/ImageCollection.java b/src/ch/epfl/xblast/client/ImageCollection.java new file mode 100644 index 0000000..231d84c --- /dev/null +++ b/src/ch/epfl/xblast/client/ImageCollection.java @@ -0,0 +1,91 @@ +package ch.epfl.xblast.client; + +import javax.imageio.ImageIO; +import java.util.HashMap; +import java.util.Map; +import java.awt.Image; +import java.io.File; +import java.util.NoSuchElementException; + +/** + * @author Timothée FLOURE (257420) + */ +public final class ImageCollection { + + /** + * Relative directory. + */ + private final String directory; + + /** + * Get the directory Object from the relative directory Name using Java Resource. + * + * @param directoryName the relative name of the directory + * @throws NoSuchElementException + * @return the File Object related to the directory + */ + private static File getDirectory(String directoryName) { + try { // Ugly! Probably a better way... + return new File(ImageCollection.class + .getClassLoader() + .getResource(directoryName) + .toURI()); + } catch (java.net.URISyntaxException e) { + throw new NoSuchElementException(); + } + } + + /** + * Maps the directory's files with IDs parsed from their names. + * + * @return a map of id to files + */ + private Map mapFilesId() { + HashMap mappedFiles = new HashMap<>(); + + for (File file : this.getDirectory(this.directory).listFiles()) { + mappedFiles.put(Integer.parseInt(file.getName()), file); + } + + return mappedFiles; + } + + /** + * Instantiates a new ImageCollection. + * + * @param directory the relative directory name. + */ + public ImageCollection(String directory) { + this.directory = directory; + } + + /** + * Returns the image corresponding to the given id. + * + * @throws java.util.NoSuchElementException if the requested image does not exists. + * @return the image corresponding to the given id + */ + public Image image(int id) { + if (this.imageOrNull(id) == null) + throw new NoSuchElementException(); + else + return this.imageOrNull(id); + } + + /** + * Returns the image corresponding to the given id. + * + * @return the image corresponding to the given id or null + */ + public Image imageOrNull(int id){ + // Ugly! Probably a better way... + if (mapFilesId().containsKey(id)) + try { + return ImageIO.read(mapFilesId().get(id)); + } catch (java.io.IOException e) { + return null; + } + else + return null; + } +} -- cgit v1.2.3