Advertisement
DulcetAirman

resize icon in Swing

Jul 29th, 2018
215
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.85 KB | None | 0 0
  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. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement