package loader;
import java.applet.Applet;
import java.applet.AudioClip;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import java.nio.file.DirectoryIteratorException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import javax.imageio.ImageIO;
public final class ResourceLoader {
public final static String ROOT = "res";
public final static String AUDIO = "audio";
public final static String IMAGES = "images";
private static ResourceLoader resLoader = new ResourceLoader();
private ResourceLoader() {};
public static URL getURL(String filePath) {
return resLoader.getClass().getResource("../" + filePath);
}
public static AudioClip getAudioClip(String filePath) { // throws Exception
AudioClip sound = Applet.newAudioClip(ResourceLoader.getURL("audio/" + filePath));
return sound;
}
public static ArrayList<String> getFileList(String parentDir, String dir) throws IOException {
Path directory = Paths.get(ROOT, parentDir, dir);
ArrayList<String> fileList = new ArrayList<String>();
try (DirectoryStream<Path> stream = Files.newDirectoryStream(directory)) {
for (Path file : stream) {
if(!Files.isDirectory(file)) {
String fileName = file.getFileName().toString();
fileList.add(fileName);
}
}
} catch (DirectoryIteratorException e) {
e.printStackTrace();
}
return fileList;
}
public static BufferedImage getImage(String filePath) throws IOException {
BufferedImage img = ImageIO.read(ResourceLoader.getURL("images/" + filePath));
return img;
}
public static ArrayList<BufferedImage> getImageArray(String filePath, int frames, int width, int height) throws IOException {
BufferedImage img = ResourceLoader.getImage(filePath);
ArrayList<BufferedImage> imgArray = new ArrayList<BufferedImage>(frames);
for (int i=0; i < frames; i++) {
imgArray.add(img.getSubimage(0 + (i * width), 0, width, height));
}
return imgArray;
}
public static ArrayList<BufferedImage> flipImageArrayHorizontal(ArrayList<BufferedImage> imgArray) {
ArrayList<BufferedImage> flippedImgArray = new ArrayList<BufferedImage>(imgArray.size());
for (int i=0; i < imgArray.size(); i++) {
AffineTransform tx = AffineTransform.getScaleInstance(-1d, 1d);
tx.translate(-imgArray.get(i).getWidth(), 0);
AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_BILINEAR);
flippedImgArray.add(op.filter(imgArray.get(i), null));
}
return flippedImgArray;
}
}