2012-10-09 84 views
0

我正在製作一個應用程序,將圖像從android設備發送到在PC上運行的java應用程序。客戶端(android)上的圖像是Bitmap,我將它轉換爲Byte Array以便通過藍牙將其發送到服務器。通過藍牙將圖像從android發送到PC

ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
ImageBitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);  
byte[] b = baos.toByteArray(); 
mBluetoothService.write(b); 

請注意,位圖來自已經壓縮的文件,所以我不需要再壓縮它。

我使用服務器(Java)的上下面的代碼:

byte[] buffer = new byte[1024*1024]; 
    int bytes; 
    bytes = inputStream.read(buffer); 
    ByteArrayInputStream bais = new ByteArrayInputStream(buffer); 
    BufferedImage image = ImageIO.read(bais); 
    ImageIO.write(image, "jpg", new File("c:/users/image.jpg")); 

有在客戶端沒有錯誤。但我在服務器端(Java應用程序)得到這個異常:

java.lang.IllegalArgumentException:im == null!

在javax.imageio.ImageIO.write(未知來源)

在javax.imageio.ImageIO.write(未知來源)

在com.luugiathuy.apps.remotebluetooth.ProcessConnectionThread.run(ProcessConnectionThread的.java:68)

在java.lang.Thread.run(來源不明)

所以ImageIO.read()不返回任何東西。它好像不能將字節數組識別爲圖像。我在互聯網上搜索,但沒有任何幫助我解決這個問題。有人有什麼主意嗎?

非常感謝!

+0

請發佈您的錯誤日誌 –

+0

java.lang.IllegalArgumentException:im == null! \t在javax.imageio.ImageIO.write(未知來源) \t在javax.imageio.ImageIO.write(未知來源) \t在com.luugiathuy.apps.remotebluetooth。ProcessConnectionThread.run(ProcessConnectionThread.java:68) \t at java.lang.Thread.run(Unknown Source) – daao87

+0

編輯您的問題併發布您的整個logcat,以便社區成員可以幫助您,而不僅僅是部分 –

回答

0

我終於明白了!恰巧客戶端(Android)創建了一個用於接收的線程和一個用於寫入的線程。所以,當我發送圖像時,它會以大塊的形式發送出去。即編寫線程暫時由Android OS暫停,所以服務器端(Java應用程序)的inputStream看到的是圖像即將分割。因此,ImageIO.read()不能成功讀取圖像,只能看到它的一部分,這就是爲什麼我得到「java.lang.IllegalArgumentException:im == null!」,因爲沒有圖像只能創建一個塊。

解決方案:

另外的形象,我也送一個字符串到服務器「文件尾」,因此它知道該文件何時完成(我認爲是有對這個更好的方法,但這是工作)。在服務器端,在一個while循環中,我接收所有字節塊,並將它們放在一起,直到收到「文件結束」爲止。代碼:

Android客戶端:

ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
    ImageBitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);  
    byte[] b = baos.toByteArray(); 
    mBluetoothService.write(b); 
    mBluetoothService.write("end of file".getBytes()); 

Java服務器:

byte[] buffer = new byte[1024]; 

    File f = new File("c:/users/temp.jpg"); 
    FileOutputStream fos = new FileOutputStream (f); 

    int bytes = 0; 
    boolean eof = false; 

    while (!eof) { 

     bytes = inputStream.read(buffer); 
     int offset = bytes - 11; 
     byte[] eofByte = new byte[11]; 
     eofByte = Arrays.copyOfRange(buffer, offset, bytes); 
     String message = new String(eofByte, 0, 11); 

     if(message.equals("end of file")) { 

      eof = true; 

     } else { 

      fos.write (buffer, 0, bytes); 

     } 

    } 
    fos.close(); 

希望它可以幫助別人。

相關問題