-->

Image uploaded from the android app space seems co

2019-08-01 12:57发布

问题:

In my android application, I need to upload a image in my Assets/Drawable/raw folder to the server. I tried the following:

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);
}

This executes fine. I am able to read the inputstream and write bytes to the DataOutputStream, the image is uploaded to the server.

Anyhow, the image at the server appears to be corrupted - only for the default image (uploaded in the 'else' block. The 'if' block image is not getting corrupted)

I also tried placing default.png in the 'raw' folder and tried the below

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

Same result here - the image at the server is corrupted.

I am starting to doubt if this is because the default.png is in the application space.

Can I get some help towards the proper way to upload an image in the application space (drawable/asset/raw)?

thanks!

nimi

回答1:

It might have to do with the buffer size? I tried two different methods to read/write a png from the assets folder and both produced a working image. I used FileOutputStream to write to the sdcard but that should not be an issue.

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();
  }
}