1

在我的 android 应用程序中,我需要将 Assets/Drawable/raw 文件夹中的图像上传到服务器。我尝试了以下方法:

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,图像被上传到服务器。

无论如何,服务器上的图像似乎已损坏-仅适用于默认图像(在“else”块中上传。“if”块图像未损坏)

我还尝试将 default.png 放在“原始”文件夹中并尝试以下操作

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

这里的结果相同 - 服务器上的图像已损坏。

我开始怀疑这是否是因为 default.png 在应用程序空间中。

我可以在应用程序空间(可绘制/资产/原始)中上传图像的正确方法方面获得一些帮助吗?

谢谢!

尼米

4

1 回答 1

0

它可能与缓冲区大小有关?我尝试了两种不同的方法从资产文件夹中读取/写入 png,并且都生成了工作图像。我使用 FileOutputStream 写入 sdcard,但这应该不是问题。

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();
  }
}
于 2011-04-28T04:34:25.853 回答