new ImageIcon(String filename)的路径问题

比如我新建一个工程CoreJava。其中有CoreJava/bin,CoreJava/src两个文件夹。

如果图像文件放在CoreJava文件夹内,则书写格式为:

 

new ImageIcon("yellow-ball.gif");

 

如果放在CoreJava/src文件夹内,则书写格式为:

 

new ImageIcon("src/yellow-ball.gif");

将此段代码放入客户端和服务端任一方都可以,让该方打开图片并显示。但需要注意的是,这段代码是基于 Swing 的 GUI 程序,需要在运行该代码的主机上启动 X 服务器,在客户端上运行可能会有问题。 如果想要在客户端和服务端之间传输图片,可以将图片转换成字节数组,然后通过 Socket 进行传输。客户端接收到字节数组后,可以将其转换为图片并显示。具体实现可以参考以下代码: 客户端: ``` public class Client { public static void main(String[] args) { try (Socket socket = new Socket("127.0.0.1", 8888)) { OutputStream outputStream = socket.getOutputStream(); FileInputStream fileInputStream = new FileInputStream("image.png"); byte[] buffer = new byte[1024]; int length; while ((length = fileInputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, length); } fileInputStream.close(); outputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } ``` 服务端: ``` public class Server { public static void main(String[] args) { try (ServerSocket serverSocket = new ServerSocket(8888)) { System.out.println("Waiting for client connection..."); Socket socket = serverSocket.accept(); System.out.println("Client connected."); InputStream inputStream = socket.getInputStream(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int length; while ((length = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, length); } byte[] imageBytes = outputStream.toByteArray(); inputStream.close(); outputStream.close(); ImageIcon imageIcon = new ImageIcon(imageBytes); JLabel label = new JLabel(imageIcon); JFrame frame = new JFrame("Image Display"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().add(label); frame.pack(); frame.setVisible(true); } catch (IOException e) { e.printStackTrace(); } } } ``` 注意:以上代码仅为示例,实际应用中需要进行错误处理和其他优化。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值