SHARE
TWEET

resize icon in Swing

DulcetAirman Jul 29th, 2018 65 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. public static Icon resizeIcon(final Icon icon, final int newWidth, final Component targetComponent) {
  2.     try {
  3.         final BufferedImage image = iconToImage(icon, targetComponent);
  4.         final int w = icon.getIconWidth(), h = icon.getIconHeight();
  5.         if (w == newWidth) return icon;
  6.         final int newHeight = (int) round(h / (w / ((double) newWidth)), 0);
  7.  
  8.         final BufferedImage bi = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_ARGB);
  9.         final Graphics2D g = (Graphics2D) bi.getGraphics();
  10.         final HashMap<Key, Object> hints = new HashMap<Key, Object>(7);
  11.         hints.put(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
  12.         hints.put(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
  13.         hints.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
  14.         hints.put(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
  15.         hints.put(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
  16.         hints.put(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_DISABLE);
  17.         hints.put(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
  18.         g.addRenderingHints(hints);
  19.         g.drawImage(image, 0, 0, newWidth, newHeight, null);
  20.         return new ImageIcon(bi);
  21.     } catch (final Exception e) {
  22.         return icon;
  23.     }
  24. }
  25.  
  26. public static BufferedImage iconToImage(final Icon icon, final Component targetComponent) {
  27.     final int w = icon.getIconWidth();
  28.     final int h = icon.getIconHeight();
  29.     GraphicsConfiguration gc = targetComponent.getGraphicsConfiguration();
  30.     if (gc == null) gc = Frame.getFrames()[0].getGraphicsConfiguration();
  31.     final BufferedImage image = gc.createCompatibleImage(w, h, Transparency.TRANSLUCENT);
  32.     final Graphics2D g = image.createGraphics();
  33.     icon.paintIcon(targetComponent, g, 0, 0);
  34.     g.dispose();
  35.     return image;
  36. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top