1 package com.android.hierarchyviewer.ui.util; 2 3 import javax.swing.Icon; 4 import javax.swing.ImageIcon; 5 import javax.imageio.ImageIO; 6 import java.io.IOException; 7 import java.awt.image.BufferedImage; 8 import java.awt.Graphics; 9 import java.awt.GraphicsEnvironment; 10 import java.awt.GraphicsConfiguration; 11 12 public class IconLoader { load(Class<?> klass, String path)13 public static Icon load(Class<?> klass, String path) { 14 try { 15 return new ImageIcon(ImageIO.read(klass.getResourceAsStream(path))); 16 } catch (IOException e) { 17 e.printStackTrace(); 18 } 19 return null; 20 } 21 getGraphicsConfiguration()22 private static GraphicsConfiguration getGraphicsConfiguration() { 23 GraphicsEnvironment environment = GraphicsEnvironment.getLocalGraphicsEnvironment(); 24 return environment.getDefaultScreenDevice().getDefaultConfiguration(); 25 } 26 isHeadless()27 private static boolean isHeadless() { 28 return GraphicsEnvironment.isHeadless(); 29 } 30 toCompatibleImage(BufferedImage image)31 public static BufferedImage toCompatibleImage(BufferedImage image) { 32 if (isHeadless()) { 33 return image; 34 } 35 36 if (image.getColorModel().equals( 37 getGraphicsConfiguration().getColorModel())) { 38 return image; 39 } 40 41 BufferedImage compatibleImage = getGraphicsConfiguration().createCompatibleImage( 42 image.getWidth(), image.getHeight(), image.getTransparency()); 43 Graphics g = compatibleImage.getGraphics(); 44 g.drawImage(image, 0, 0, null); 45 g.dispose(); 46 47 return compatibleImage; 48 } 49 } 50