【问题标题】:Android Get Local File BytesAndroid 获取本地文件字节
【发布时间】:2009-11-27 05:03:42
【问题描述】:

我正在尝试获取手机本地保存的图像的字节数组。我正在使用代码:

@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.moveToFirst()) {
          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;
      }
    } 
}

但它会在

上抛出 FileNotFound exception
ImgIs = new FileInputStream(Img)

如何获取字节?

【问题讨论】:

  • 既然我回答了自己的问题,我应该把问题留在这里还是删除?

标签: android image


【解决方案1】:

没关系,我找到了答案,见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);

【讨论】:

    【解决方案2】:

    这是我在上一个项目中使用的另一种方式:

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

    在上面的代码中,我将位图的内容以 100% 的质量写入 outputStream。 希望这会有所帮助

    【讨论】:

      猜你喜欢
      • 2020-12-13
      • 1970-01-01
      • 2013-04-14
      • 1970-01-01
      • 2014-04-03
      • 1970-01-01
      • 2016-05-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多