diff --git a/src/edu/calpoly/spritely/ImageTile.java b/src/edu/calpoly/spritely/ImageTile.java index 4d0c74a..b21c7a6 100644 --- a/src/edu/calpoly/spritely/ImageTile.java +++ b/src/edu/calpoly/spritely/ImageTile.java @@ -31,6 +31,7 @@ import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; +import java.net.URL; import javax.imageio.ImageIO; /** @@ -76,24 +77,60 @@ public ImageTile(File imageFile, Size size, char text) System.err.println("*** Error reading " + imageFile); throw ex; } - if (im.getWidth() != size.width || im.getHeight() != size.height) { - double scaleX = ((double) size.width) / im.getWidth(); - double scaleY = ((double) size.height) / im.getHeight(); - BufferedImage after = - new BufferedImage(size.width, size.height,im.getType()); - AffineTransform scale = - AffineTransform.getScaleInstance(scaleX, scaleY); - AffineTransformOp scaleOp = - new AffineTransformOp(scale, - AffineTransformOp.TYPE_BILINEAR); - scaleOp.filter(im, after); - im = after; + im = scaleImage(im, size); + } + this.image = im; + this.text = text; + } + + /** + * Create a ImageTile with the given image, at the given size, + * and that is represented by the given character when in text + * mode. The image may contain transparent and semi-transparent pixels. + * + * @param imageURL A url referring to a valid image file + * @param size The size of a tile, in pixels + * @param text The character representation of this tile + * in text mode + * @throws IOException if there is an error reading the image + * @see ImageIO#read(File) + */ + public ImageTile(URL imageURL, Size size, char text) + throws IOException + { + BufferedImage im; + if (GraphicsEnvironment.getLocalGraphicsEnvironment().isHeadless()) { + im = null; + } else { + try { + im = ImageIO.read(imageURL); + } catch (IOException ex) { + System.err.println("*** Error reading " + imageURL); + throw ex; } + im = scaleImage(im, size); } this.image = im; this.text = text; } + private static BufferedImage scaleImage(BufferedImage im, Size size) { + if (im.getWidth() != size.width || im.getHeight() != size.height) { + double scaleX = ((double) size.width) / im.getWidth(); + double scaleY = ((double) size.height) / im.getHeight(); + BufferedImage after = + new BufferedImage(size.width, size.height,im.getType()); + AffineTransform scale = + AffineTransform.getScaleInstance(scaleX, scaleY); + AffineTransformOp scaleOp = + new AffineTransformOp(scale, + AffineTransformOp.TYPE_BILINEAR); + scaleOp.filter(im, after); + im = after; + } + return im; + } + @Override public void paint(Graphics2D g, Size size) { g.drawImage(image, 0, 0, null);