Java Swing setIconImage(new ImageIcon(byte []))不起作用

时间:2018-02-17 09:43:48

标签: java swing

我的应用程序的Java Swing界面,并想在左上角设置我的个人图标。

我的代码:

File fimg = new File("D:\\logo.png");
BufferedImage img = ImageIO.read(fimg);

WritableRaster raster = img.getRaster();
DataBufferByte data   = (DataBufferByte) raster.getDataBuffer();

ImageIcon icon = new ImageIcon(data.getData());
setIconImage(icon.getImage());

此代码不起作用。

如果我改变了这个

new ImageIcon(data.getData()); //ImageIcon(byte[] x)

new ImageIcon(img); //ImageIcon(Image x)

工作正常。

如何让ImageIcon(byte[])工作,以便将图像存储为字节?

1 个答案:

答案 0 :(得分:0)

试试这个:

import java.awt.GridLayout;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class SwingTest {

    SwingTest() {

        JFrame frame=new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLayout(new GridLayout(1,2));

        BufferedImage img = null;
        try {
            URL url = new URL("http://www.digitalphotoartistry.com/rose1.jpg");
            img = ImageIO.read(url);
        } catch (IOException ex) {  ex.printStackTrace();}

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            ImageIO.write(img, "JPEG", baos);
        } catch (IOException ex) {ex.printStackTrace();      }

        frame.add(new JLabel(new ImageIcon(img)));
        frame.add(new JLabel(new ImageIcon(baos.toByteArray())));
        frame.pack();
        frame.setVisible(true);
    }

    public static void main (String[] agrs) {
        new SwingTest();
    }
}