【问题标题】:Image uploaded from the android app space seems corrupted从 android 应用程序空间上传的图像似乎已损坏
【发布时间】:2011-04-27 23:23:19
【问题描述】:

在我的 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 在应用程序空间中。

我可以就在应用程序空间(drawable/asset/raw)中上传图像的正确方法获得一些帮助吗?

谢谢!

尼米

【问题讨论】:

    标签: android assets fileinputstream


    【解决方案1】:

    这可能与缓冲区大小有关?我尝试了两种不同的方法从资产文件夹中读取/写入 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();
      }
    }
    

    【讨论】:

    • 您好 Aleadam,感谢您的详细回复。我尝试了两种方式,但略有不同 - 尝试写入 HttpURLConnection 的 DataOutputStream。没运气。无论如何,我觉得你是对的,如果它可以从应用程序空间写入 SDCard,它也应该可以写入服务器。会继续努力。
    猜你喜欢
    • 2018-05-22
    • 1970-01-01
    • 1970-01-01
    • 2011-10-23
    • 2018-05-17
    • 2013-05-23
    • 2020-03-18
    • 2018-08-09
    • 2016-01-14
    相关资源
    最近更新 更多