package ui.view; import java.awt.Image; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import javax.imageio.ImageIO; public class Util { /** * 30x30 pixel FileNotFound Icon, which can be shown without using I/O operations */ static private Image defaultImage = createDefaultImage(); /** * creates the default Image * @return 30x30 Image, showing a red cross */ private static Image createDefaultImage() { BufferedImage def = new BufferedImage(30,30,BufferedImage.TYPE_BYTE_INDEXED); for(int x = 0; x < 30; x++) for(int y = 0; y < 30; y++){ if(x == 29 || y == 29) //Border Bottom/Left -> Light Grey def.setRGB(x, y, 13158600); else if(x == 0 || y == 0) //Border Top/Right -> Dark Grey def.setRGB(x, y, 6316128); else if((x == y || x == 31 - y) && 6 < x && x < 25) //Red Cross in the middle def.setRGB(x, y, 13107200); else //all other Pixels are white def.setRGB(x, y, 16777215); } return def; } static Image loadImage(Object origin, String url, int w, int h, int scale){ return loadImage(origin,url).getScaledInstance(w, h, scale); } static Image loadImage(Object origin, String url, int w, int h){ return loadImage(origin,url,w,h, Image.SCALE_SMOOTH); } static Image loadImage(Object origin, String url){ try { return ImageIO.read(loadStream(origin, url)); } catch (IOException e) { //System.err.println("Warning: '" + url + "' loading failed!"); e.printStackTrace(); return defaultImage; } } static InputStream loadStream(Object origin, String url){ InputStream o=origin.getClass().getResourceAsStream(url); if(o!=null)return o; else{ //System.out.println("Loading of \""+url+"\" as local resource failed.\nWill attempt to load as File."); boolean rootSymbol=false; //Whether url starts with a / or \ switch(url.charAt(0)){ //So we can make sure to construct res/path correctly. case '/':case '\\':rootSymbol=true; } try { //I am checking, whether the requested File is an internal resource. //If it is, res/url has to be used, otherwise url. //Mixed separators might cause problems. Will fix later. File f=new File(url); if(!f.exists()/*||!f.getAbsolutePath().equals(url)*/)url="res"+(rootSymbol?"":"/")+url; return new FileInputStream(url); } catch (FileNotFoundException e1) { e1.printStackTrace(); } return null; } } }