2011-04-27 55 views
1

在我的android應用程序中,我需要將我的Assets/Drawable/raw文件夾中的圖像上傳到服務器。 我試過以下內容:從android應用程序空間上傳的圖像似乎已損壞

InputStream fileInputStream;  
if(imageChanged) {  
    File file = New File("filename");  
    fileInputStream = new FileInputStream(file); 
}else {  
    fileInputStream = ctx.getAssets().open("default.png");  
} 
int bytesAvailable;  
byte[] buffer = new byte[102400];  
while((bytesAvailable = fileInputStream.available()) > 0) {  
    int bufferSize = Math.min(bytesAvailable, 102400);  
    if(bufferSize<102400){  
     buffer = new byte[bufferSize];  
    } 
    int bytesRead = fileInputStream.read(buffer, 0,bufferSize); 
    dos.write(buffer, 0, bytesRead); 
} 

這個執行得很好。我能夠讀取輸入流並將字節寫入DataOutputStream,將圖像上傳到服務器。

總之,在服務器上的圖像似乎已損壞 - (在「其他」塊上傳的「如果」塊圖像在不損壞),只爲默認圖像

我也試過把默認在'原始'文件夾中,並嘗試以下

fileInputStream = ctx.getResources().openRawResource(R.drawable.default); 

相同的結果在這裏 - 服務器上的映像已損壞。

我開始懷疑這是否是因爲default.png位於應用程序空間中。

我可以通過正確的方式在應用程序空間(drawable/asset/raw)中上傳圖像嗎?

謝謝!

nimi

回答

0

它可能與緩衝區大小有關嗎?我嘗試了兩種不同的方法來從資源文件夾讀取/寫入png,並且都生成了一個工作映像。我用FileOutputStream寫入SD卡,但這不應該是一個問題。

InputStream is, is2; 
FileOutputStream out = null, out2 = null; 
try { 
    //method 1: compressing a Bitmap 
    is = v.getContext().getAssets().open("yes.png"); 
    Bitmap bmp = BitmapFactory.decodeStream(is); 
    String filename = Environment.getExternalStorageDirectory().toString()+File.separator+"yes.png"; 
    Log.d("BITMAP", filename); 
    out = new FileOutputStream(filename); 
    bmp.compress(Bitmap.CompressFormat.PNG, 90, out); 

    //method 2: Plain stream IO 
    String filename2 = Environment.getExternalStorageDirectory().toString()+File.separator+"yes2.png"; 
    out2 = new FileOutputStream(filename2); 
    Log.d("BITMAP", filename2); 
    int r, i=0; 
    is2 = v.getContext().getAssets().open("yes.png"); 
    while ((r = is2.read()) != -1) { 
    Log.d ("OUT - byte " + i, "Value: " + r); 
    out2.write(r); 
    i++; 
    } 

} catch (IOException e) { 
    e.printStackTrace(); 
} finally { 
    try { 
    if (out != null) 
     out.close(); 
    if (out2 != null) 
     out2.close(); 
    } catch (IOException e) { 
    e.printStackTrace(); 
    } 
} 
+0

嗨Aleadam,謝謝你的詳細回覆。我嘗試了兩種方式,略有不同 - 嘗試寫入HttpURLConnection的DataOutputStream。沒有運氣。無論如何,我覺得你是對的,如果它可以從應用程序空間寫入SDCard,它也應該可寫入服務器。將繼續嘗試。 – nimmi 2011-04-29 18:22:16