【问题标题】:Saving an icon on a jLabel as an Image on the hard disk将 jLabel 上的图标保存为硬盘上的图像
【发布时间】:2012-10-02 23:57:51
【问题描述】:

我的代码中生成了一个图像图标,我按照以下代码将其作为图标放在标签上:

ImageIcon icon = new ImageIcon(barcode.drawBarcode());
jLabel36.setIcon(icon);

现在我的问题是如何将 ImageIcon 类型更改为 Image 并将其保存在硬盘上。当我尝试将 ImageIcon 类型转换为 Image 时,出现以下错误:

java.lang.ClassCastException: javax.swing.ImageIcon 无法转换为 java.awt.Image

任何人都可以建议我如何在类型转换和保存图像方面完成这项任务。

【问题讨论】:

    标签: java image swing jlabel imageicon


    【解决方案1】:

    只需使用getImage():

    // get image from imageicon
    Image image = icon.getImage();
    
    // cast it to bufferedimage
    BufferedImage buffered = (BufferedImage) image;
    
    try {
        // save to file
        File outputfile = new File("saved.png");
        ImageIO.write(buffered, "png", outputfile);
    } catch (IOException e) {
        e.printStackTrace();
    }
    

    【讨论】:

    • 只要你有ImageIcon的引用,否则你需要将图标绘制到缓冲图像的图形上下文中
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-16
    • 1970-01-01
    • 2011-02-08
    • 2011-10-31
    相关资源
    最近更新 更多