1 22 23 package de.laures.cewolf.util; 24 25 import java.awt.Component ; 26 import java.awt.Graphics ; 27 import java.awt.Image ; 28 import java.awt.MediaTracker ; 29 import java.awt.image.BufferedImage ; 30 import java.awt.image.ColorModel ; 31 import java.awt.image.PixelGrabber ; 32 33 import org.apache.commons.logging.Log; 34 import org.apache.commons.logging.LogFactory; 35 36 40 public class ImageHelper { 41 42 private static final Component comp = new Component () { }; 43 private static final MediaTracker tracker = new MediaTracker (comp); 44 private static final Log log = LogFactory.getLog(ImageHelper.class); 45 46 47 private ImageHelper() { 48 } 49 50 public static final Image loadImage(String fileName) { 51 final Image image = java.awt.Toolkit.getDefaultToolkit().getImage(fileName); 52 synchronized(tracker) { 53 tracker.addImage(image, 0); 54 try { 55 tracker.waitForID(0, 0); 56 } catch (InterruptedException e) { 57 log.debug("INTERRUPTED while loading Image"); 58 } 59 tracker.removeImage(image, 0); 60 } 61 return image; 62 } 63 64 public static BufferedImage loadBufferedImage(String fileName) { 65 Image image = loadImage(fileName); 66 if (image instanceof BufferedImage ) { 67 return (BufferedImage )image; 68 } 69 74 int width = (int)Math.max(1.0, image.getWidth(null)); 75 int height = (int)Math.max(1.0, image.getHeight(null)); 76 BufferedImage bimage = new BufferedImage (width, height, BufferedImage.TYPE_INT_RGB); 78 final Graphics g = bimage.createGraphics(); 79 g.drawImage(image, 0, 0, null); 80 g.dispose(); 81 return bimage; 82 } 83 84 public static boolean hasAlpha(Image image) { 85 if (image instanceof BufferedImage ) { 86 return ((BufferedImage )image).getColorModel().hasAlpha(); 87 } 88 PixelGrabber pg = new PixelGrabber (image, 0, 0, 1, 1, false); 89 try { 90 pg.grabPixels(); 91 } catch (InterruptedException e) { 92 e.printStackTrace(); 93 } 94 ColorModel cm = pg.getColorModel(); 95 if(cm == null){ 96 return false; 97 } 98 return cm.hasAlpha(); 99 } 100 101 public static BufferedImage createImage(int width, int height) { 102 return new BufferedImage (width, height, BufferedImage.TYPE_INT_RGB); 104 } 105 106 } 107 | Popular Tags |