开发者

Android Get Local File Bytes

I'm trying to get a byte array of an image saved locally on the phone. I'm using the code:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.upload);

    // Look in the Device
    startActivityForResult(new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI), 1);
    // Look in the SD Card
    // startActivityForResult(new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI), 1);
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
  super.onActivityResult(requestCode, resultCode, data);
  if (requestCode == 1)
    if (resultCode == Activity.RESULT_OK) {
      Uri selectedImage = data.getData();
      Cursor Cur = Upload.this.managedQuery(selectedImage, null, null, null,null);
      if (Cur.moveToFir开发者_开发知识库st()) {
          File Img = new File(selectedImage.getPath());
          long Length = Cur.getLong(Cur.getColumnIndex(ImageColumns.SIZE));
          byte[] B = new byte[(int)Length-1];
          FileInputStream ImgIs;
          try {
            ImgIs = new FileInputStream(Img);
            ImgIs.read(B);
          } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
          } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        int i = B.length;
      }
    } 
}

But it throws a FileNotFound exception on

ImgIs = new FileInputStream(Img)

How can I get the Bytes?


Nevermind, I found the answer, see http://www.mail-archive.com/android-developers@googlegroups.com/msg66448.html

Cursor cursor = getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();

int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
String absoluteFilePath = cursor.getString(idx);
FileInputStream fis = new FileInputStream(absoluteFilePath);


This is another way I used in my last project:

bitmap.compress(CompressFormat.JPEG, 100, outputStream);

In above code, I write the content of bitmap to outputStream with 100% quality. Hope this helps

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜