2012-07-11 23 views
0

我使用this accepted answer提供的代碼通過Java套接字發送文件列表。我的目標是獲得圖像列表。我想要做的是在將這些圖像寫入磁盤之前,將這些圖像直接讀入內存中作爲BufferedImages。但是,我第一次嘗試使用ImageIO.read(bis)(再次參見附加問題)失敗,因爲它試圖在第一個映像文件結束時繼續讀取數據。如何將流數據直接加載到BufferedImage中

我目前的想法是將數據從套接字寫入新的輸出流,然後從輸入流中讀取該流,該輸入流傳遞給ImageIO.read()。這樣,我可以按程序正在執行的方式逐字節地寫入它,但將它發送到BufferedImage而不是文件。但是我不確定如何將輸出流鏈接到輸入流。

任何人都可以推薦簡單的編輯上面的代碼,或提供另一種方法做到這一點?

回答

1

爲了在將圖像寫入磁盤之前讀取圖像,您需要使用ByteArrayInputStream。 http://docs.oracle.com/javase/6/docs/api/java/io/ByteArrayInputStream.html

基本上,它會創建一個從指定字節數組中讀取的輸入流。所以,你會讀出圖像長度,那麼它的名稱,然後字節的長度量,創建ByteArrayInputStream的,並把它傳遞給ImageIO.read

例片段:

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(); 
相關問題