【问题标题】:How to load streamed data directly into a BufferedImage如何将流数据直接加载到 BufferedImage
【发布时间】:2012-07-11 05:10:48
【问题描述】:
我正在使用this accepted answer 提供的代码通过Java 中的套接字发送文件列表。我的目标是接收图像列表。我想做的是将这些图像以BufferedImages 的形式直接读入内存,然后再将它们写入磁盘。但是,我的第一次尝试是使用 ImageIO.read(bis)(再次参见附加的问题)失败了,因为它试图在第一个图像文件的末尾继续读取。
我目前的想法是将数据从套接字写入新的输出流,然后从传递给ImageIO.read() 的输入流中读取该流。这样,我可以像程序当前正在执行的那样逐字节编写它,但将其发送到BufferedImage而不是文件。但是我不确定如何将输出流链接到输入流。
任何人都可以推荐对上面的代码进行简单的编辑,或者提供另一种方法吗?
【问题讨论】:
标签:
java
sockets
inputstream
bufferedimage
outputstream
【解决方案1】:
为了在将图像写入磁盘之前读取图像,您需要使用 ByteArrayInputStream。 http://docs.oracle.com/javase/6/docs/api/java/io/ByteArrayInputStream.html
基本上,它创建一个从指定字节数组读取的输入流。因此,您将读取图像长度,然后是名称,然后是字节长度,创建 ByteArrayInputStream,并将其传递给 ImageIO.read
示例 sn-p:
long fileLength = dis.readLong();
String fileName = dis.readUTF();
byte[] bytes = new byte[fileLength];
dis.readFully(bytes);
BufferedImage bimage = ImageIO.read(new ByteArrayInputStream(bytes));
或使用您引用的其他答案中的代码:
String dirPath = ...;
ServerSocket serverSocket = ...;
Socket socket = serverSocket.accept();
BufferedInputStream bis = new BufferedInputStream(socket.getInputStream());
DataInputStream dis = new DataInputStream(bis);
int filesCount = dis.readInt();
File[] files = new File[filesCount];
for(int i = 0; i < filesCount; i++)
{
long fileLength = dis.readLong();
String fileName = dis.readUTF();
byte[] bytes = new byte[fileLength];
dis.readFully(bytes);
BufferedImage bimage = ImageIO.read(new ByteArrayInputStream(bytes));
//do some shit with your bufferedimage or whatever
files[i] = new File(dirPath + "/" + fileName);
FileOutputStream fos = new FileOutputStream(files[i]);
BufferedOutputStream bos = new BufferedOutputStream(fos);
bos.write(bytes, 0, fileLength);
bos.close();
}
dis.close();