2010-10-29 149 views
0

我正在嘗試從服務器上拉出.jpg圖像,並將其顯示爲,並將其顯示爲EncodedImage。因爲這個.jpg可能非常大,所以我想將.jpg保存到一個文件並從那裏讀取,所以我沒有把所有東西都放在內存中。Blackberry:下載並顯示.jpg圖像

我面對的問題是,Connector.open(「http.url.com/file.jpg」)要麼拋出一個IOException與消息「錯誤的插座ID」,要麼是拋出一個ClassCastException當我嘗試打開一個FileConnection到URL。這裏是什麼,我已經試過一個例子:

try { 
     FileConnection fileIn = (FileConnection)Connector.open(fileURL); 
     FileConnection fileOut = (FileConnection)Connector.open(fileDest); 

     if(!fileOut.exists()) 
      fileOut.create(); 

     InputStream is = fileIn.openInputStream(); 
     OutputStream os = fileOut.openOutputStream(); 

     while(fileIn.canRead() && fileOut.canWrite()){ 
      os.write(is.read()); 
     } 

     is.close(); 
     os.close(); 

     fileIn.close(); 
     fileOut.close(); 

     EncodedImage image = EncodedImage.getEncodedImageResource(fileDest); 

     UiApplication.getUiApplication().pushScreen(new ZoomScreen(image)); 

    } catch (Exception e) { 
     e.printStackTrace(); 
    } 

我得到這個最RIM的,但我失去了一些東西。我知道url是正確的,因爲當我從同一臺服務器流式傳輸音頻時,我使用相同的格式。當我嘗試連接到服務器時,第一行會引發異常。

有沒有人有這方面的經驗?

回答

1

想通了。

try { 
    HttpConnection conn = (HttpConnection) Connector.open(fileURL); 
    InputStream fileIn = conn.openInputStream(); 

    ByteArrayOutputStream os = new ByteArrayOutputStream(); 

    for(int i = fileIn.read(); i > -1; i = fileIn.read()){ 
     os.write(i); 
    } 

    byte[] data = os.toByteArray(); 

    EncodedImage image = EncodedImage.createEncodedImage(data, 0, data.length); 

    UiApplication.getUiApplication().pushScreen(new ZoomScreen(image)); 

} catch (Exception e) { 
    e.printStackTrace(); 
} 

我希望其他人會覺得這有用。

1
public void run(){ 
    try{ 
     StreamConnection streamC = (StreamConnection) Connector.open(url+";deviceside=true"); 
     InputStream in = streamC.openInputStream(); 

     byte[] data = new byte[4096]; 
     data = IOUtilities.streamToBytes(in); 
     in.close(); 
      EncodedImage eImage = EncodedImage.createEncodedImage(data, 0, data.length); 
     } 
    catch(Exception e) 
     { 
      e.printStackTrace(); 
     } 
+0

感謝您的額外的輸入,但你在這裏不會爲一切工作。你只用4kB讀取,但如果文件大於4kB,該怎麼辦?考慮到大多數JPG不是很大,你的大多數情況下都適用,但不適合所有的情況。 – mtmurdock 2011-03-23 15:01:38