 |
Yet again I'm stealing from Abuse (quite ironic given the name I guess - The usual please edit/modify this if something is incorrect/unclear
Loading [managed] images with ImageIO
Code example modified (basically a copy) from http://www.javagaming.org/cgi-bin/JGNetForums/YaBB.cgi?board=2D;action=display;num=1058722081;start=27#27
import java.awt.*;
import java.awt.image.*;
public class ImageLoader {
final GraphicsConfiguration gc;
public ImageLoader(GraphicsConfiguration gc) {
if(gc==null) {
gc = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice ().getDefaultConfiguration();
}
this.gc = gc;
}
public BufferedImage loadImage(String resource) {
try {
BufferedImage src = javax.imageio.ImageIO.read(getClass().getResource(resource));
//In Java 1.4 and earlier Images returned from ImageIO are NOT managed images
//Therefore, we copy it into a ManagedImage
BufferedImage dst = gc.createCompatibleImage(src.getWidth(),src.getHeight(),src.getColorModel(),src.getTransparency());
// Setting transparency
Graphics2D g2d = dst.createGraphics();
g2d.setComposite(AlphaComposite.Src);
// Copy image
g2d.drawImage(src,0,0,null);
g2d.dispose();
return dst;
} catch(java.io.IOException ioe) {
ioe.printStackTrace();
return null;
}
}
}
</
|