【问题标题】:Android Bitmap from URI来自 URI 的 Android 位图
【发布时间】:2015-01-26 21:17:41
【问题描述】:

我拍照并将结果保存在一个文件中。结果照片存在,我可以用文件管理器打开它。但是,我无法将该文件转换为有效的位图。我尝试了不同的方法,包括 BitmapFactory,但它总是返回一个空位图。

生成的 URI,即 mImageUri,是

file:///storage/emulated/0/Pictures/IMG_20150126_180346_1663372760.jpg

和路径

/storage/emulated/0/Pictures/IMG_20150126_180346_1663372760.jpg

代码如下。

Utils 类创建新的图像文件

public static File createImageFile() throws IOException {
    // Create an image file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    String imageFileName = "IMG_" + timeStamp + "_";
    File storageDir = Environment.getExternalStoragePublicDirectory(
            Environment.DIRECTORY_PICTURES);
    File image = File.createTempFile(
            imageFileName,  /* prefix */
            ".jpg",         /* suffix */
            storageDir      /* directory */
    );

    return image;
}

在 onCreate() 中创建 mImageUri

try {
        mPhotoFile = Utils.createImageFile();
        mImageUri = Uri.fromFile(mPhotoFile);
    } catch (IOException ex) {
        Toast.makeText(this, getString(R.string.error_something_wrong_happened), Toast.LENGTH_LONG).show();
    }

调用相机意图

Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (takePhotoIntent.resolveActivity(getPackageManager()) != null && mImageUri != null) {

         takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT, mImageUri);
         startActivityForResult(takePhotoIntent, REQUEST_CAMERA);
}

解析结果

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {

    if (requestCode == REQUEST_CAMERA && resultCode == RESULT_OK) {
    //Unable to get Bitmap from mImageUri
    try {
        Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), mImageUri);
        Log.d(TAG, "bitmap exists " + bitmap);
    } catch (IOException e) {
        e.printStackTrace();
    }
    }

}

Android 版本为 4.4.4

【问题讨论】:

  • 当你说你“没有运气”是什么意思,它会崩溃,它会返回一个空位图吗?
  • 请更具体地发布您的结果、例外情况等。
  • 它返回一个空位图,对

标签: android android-intent bitmap android-camera


【解决方案1】:

也许迟到了,但我用“bitmap=BitmapFactory.decodeFile(uri);”解决了我的问题 疯狂的是我不需要直接输入“file://”bcos BitmapFactory 接受“/storage/emulated/......../bla.jpeg”

在我尝试使用之前:
位图 = MediaStore.Images.Media.getBitmap(this.getContentResolver(), Uri.parse(uri));

但是没用……

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-07-22
    • 1970-01-01
    • 2023-03-22
    • 2014-03-13
    • 2019-11-15
    • 2013-11-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多