当前位置: 首页 > 面试题库 >

如何将图标转换为图像

孙莫希
2023-03-14
问题内容

我正在尝试使用以下代码将Icon(javax.swing.Icon)转换为Image(java.awt.Image):

private Image iconToImage(Icon icon)
{
    if(icon instanceof ImageIcon)
    {
        return ((ImageIcon) icon).getImage();
    }
    else
    {
        BufferedImage image = new BufferedImage(icon.getIconWidth(), icon.getIconHeight(), BufferedImage.TYPE_INT_RGB);
        icon.paintIcon(null, image.getGraphics(), 0, 0);
        return image;
    }
}

问题是,paintIcon函数在NullPointerException上抛出image.getGraphics()

对于记录,该icon值为默认CheckBox图标(通过获取UIManager.getIcon("CheckBox.icon")

以下是引发异常的详细信息:

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at com.sun.java.swing.plaf.windows.WindowsIconFactory$CheckBoxIcon.paintIcon(WindowsIconFactory.java:306)
    at utils.WarningRenderer.iconToImage(WarningRenderer.java:50)
    at utils.WarningRenderer.<init>(WarningRenderer.java:38)
    at deliveryexpress.DeliveryExpressView.setWarnings(DeliveryExpressView.java:278)
    at deliveryexpress.DeliveryExpressView.updateLists(DeliveryExpressView.java:218)
    at deliveryexpress.DeliveryExpressView.access$1100(DeliveryExpressView.java:47)
    at deliveryexpress.DeliveryExpressView$5.addCheck(DeliveryExpressView.java:183)
    at org.japura.gui.model.DefaultListCheckModel.fireCheckListModelListeners(Unknown Source)
    at org.japura.gui.model.DefaultListCheckModel.fireAddCheckListModelListeners(Unknown Source)
    at org.japura.gui.model.DefaultListCheckModel.addCheck(Unknown Source)
    at org.japura.gui.CheckList$1.mouseClicked(Unknown Source)
    at java.awt.AWTEventMulticaster.mouseClicked(AWTEventMulticaster.java:253)
    at java.awt.Component.processMouseEvent(Component.java:6292)
    at javax.swing.JComponent.processMouseEvent(JComponent.java:3267)
    at java.awt.Component.processEvent(Component.java:6054)
    at java.awt.Container.processEvent(Container.java:2041)
    at java.awt.Component.dispatchEventImpl(Component.java:4652)
    at java.awt.Container.dispatchEventImpl(Container.java:2099)
    at java.awt.Component.dispatchEvent(Component.java:4482)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4577)
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4247)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4168)
    at java.awt.Container.dispatchEventImpl(Container.java:2085)
    at java.awt.Window.dispatchEventImpl(Window.java:2478)
    at java.awt.Component.dispatchEvent(Component.java:4482)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:644)
    at java.awt.EventQueue.access$000(EventQueue.java:85)
    at java.awt.EventQueue$1.run(EventQueue.java:603)
    at java.awt.EventQueue$1.run(EventQueue.java:601)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87)
    at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:98)
    at java.awt.EventQueue$2.run(EventQueue.java:617)
    at java.awt.EventQueue$2.run(EventQueue.java:615)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:614)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)

如果您需要更多详细信息,请告诉我,我将编辑我的信息以添加它们。

谢谢!


问题答案:

刚刚找到了一个代码段,如果您想更频繁地包装那些表现不佳的LAF提供的图标,可能会有所帮助:

/**
 * Some ui-icons misbehave in that they unconditionally class-cast to the 
 * component type they are mostly painted on. Consequently they blow up if 
 * we are trying to paint them anywhere else (f.i. in a renderer).  
 * 
 * This Icon is an adaption of a cool trick by Darryl Burke/Rob Camick found at
 * http://tips4java.wordpress.com/2008/12/18/icon-table-cell-renderer/#comment-120
 * 
 * The base idea is to instantiate a component of the type expected by the icon, 
 * let it paint into the graphics of a bufferedImage and create an ImageIcon from it.
 * In subsequent calls the ImageIcon is used. 
 * 
 */
public static class SafeIcon implements Icon {

    private Icon wrappee;
    private Icon standIn;

    public SafeIcon(Icon wrappee) {
        this.wrappee = wrappee;
    }

    @Override
    public int getIconHeight() {
        return wrappee.getIconHeight();
    }

    @Override
    public int getIconWidth() {
        return wrappee.getIconWidth();
    }

    @Override
    public void paintIcon(Component c, Graphics g, int x, int y) {
        if (standIn == this) {
            paintFallback(c, g, x, y);
        } else if (standIn != null) {
            standIn.paintIcon(c, g, x, y);
        } else {
            try {
               wrappee.paintIcon(c, g, x, y); 
            } catch (ClassCastException e) {
                createStandIn(e, x, y);
                standIn.paintIcon(c, g, x, y);
            }
        }
    }

    /**
     * @param e
     */
    private void createStandIn(ClassCastException e, int x, int y) {
        try {
            Class<?> clazz = getClass(e);
            JComponent standInComponent = getSubstitute(clazz);
            standIn = createImageIcon(standInComponent, x, y);
        } catch (Exception e1) {
            // something went wrong - fallback to this painting
            standIn = this;
        } 
    }

    private Icon createImageIcon(JComponent standInComponent, int x, int y) {
        BufferedImage image = new BufferedImage(getIconWidth(),
                getIconHeight(), BufferedImage.TYPE_INT_ARGB);
          Graphics g = image.createGraphics();
          try {
              wrappee.paintIcon(standInComponent, g, 0, 0);
              return new ImageIcon(image);
          } finally {
              g.dispose();
          }
    }

    /**
     * @param clazz
     * @throws IllegalAccessException 
     */
    private JComponent getSubstitute(Class<?> clazz) throws IllegalAccessException {
        JComponent standInComponent;
        try {
            standInComponent = (JComponent) clazz.newInstance();
        } catch (InstantiationException e) {
            standInComponent = new AbstractButton() {

            };
            ((AbstractButton) standInComponent).setModel(new DefaultButtonModel());
        } 
        return standInComponent;
    }

    private Class<?> getClass(ClassCastException e) throws ClassNotFoundException {
        String className = e.getMessage();
        className = className.substring(className.lastIndexOf(" ") + 1);
        return Class.forName(className);

    }

    private void paintFallback(Component c, Graphics g, int x, int y) {
        g.drawRect(x, y, getIconWidth(), getIconHeight());
        g.drawLine(x, y, x + getIconWidth(), y + getIconHeight());
        g.drawLine(x + getIconWidth(), y, x, y + getIconHeight());
    }

}

要在您的代码段中使用,只需传递任意组件

    icon = new SafeIcon(icon);
    BufferedImage image = new BufferedImage(icon.getIconWidth(), icon.getIconHeight(), BufferedImage.TYPE_INT_RGB);
    icon.paintIcon(new JPanel(), image.getGraphics(), 0, 0);


 类似资料:
  • 问题内容: 我想将UIView转换为图像并将其保存在我的应用程序中。有人可以告诉我如何拍摄视图的屏幕截图或将其转换为图像,以及将其保存在应用程序(而不是相机胶卷)中的最佳方法是什么?这是该视图的代码: 问题答案: 例如,如果我有一个尺寸视图:100 100时50 50。我可以使用以下屏幕截图:

  • 我想把openCV Mat文件转换成GDI+位图图像。我找不到任何关于如何做到这一点的信息?

  • 我正在一个图片库网站上工作,我认为拥有模态图片将是一个很好的补充。在w3schools指南和其他一些资源的帮助下,我成功地为我的规范创建了工作模式图像。然而,我也希望在模式中的标题的后半部分在单击时作为指向另一个页面的链接,但我无法让它工作。 w3schools的JavaScript根据所讨论图像的属性中的文本添加标题。但是,由于它已经是一个属性,因此我无法将标题的后半部分用

  • 有没有更好的方法来转换贴图

  • 问题内容: 您能否指导我如何将图像从URL转换为base64编码? 问题答案: 我认为应该是:

  • 问题内容: 一周前,我开始学习python,并希望编写一个小程序将电子邮件转换为图像(.png),以便可以在论坛上共享它,而不必冒大量垃圾邮件的风险。 似乎python标准库不包含可以执行此操作的模块,但我发现有一个适用于此的模块()。 我的问题是我似乎无法正常工作。 所以基本上我的问题是: 如何在图像上绘制文本。 如何创建空白(白色)图像 有没有一种方法可以在不实际创建文件的情况下执行此操作,以