gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 10:42:18 25 4
gpt4 key购买 nike

我的应用程序有 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);//图像图标(图像x)

工作正常。

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

最佳答案

试试这个:

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();
}
}

关于Java Swing setIconImage(new ImageIcon(byte[])) 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48839941/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com