当前位置: 首页 > 知识库问答 >
问题:

拍摄图像捕获后在onActivityResult中获取空uri重复]

卫琛
2023-03-14

我正在开发一个android应用程序,我需要从应用程序中获取图像捕获,并返回捕获<code>uri

< code > uri = data . get data();

此外,我尝试从位图中获取uri,如下所示:

位图照片=(位图)data.getExtras(). get("data"); uri=getImageUri(getApplication ationContext(),照片);

但仍然不起作用。

button2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if(hasStoragePermission(IMAGE_CAPTURE)){
                Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
                    startActivityForResult(takePictureIntent, IMAGE_CAPTURE);
                }
            }
        }
    });
}

@Override
protected void onActivityResult(int requestCode, final int resultCode, Intent data) {
    switch(requestCode) {
        case 0: {
            if (requestCode == PICK_PHOTO_FOR_AVATAR && resultCode == Activity.RESULT_OK) {
                if (data == null) {
                    Toast.makeText(getApplicationContext(), "error selecting file!, Please try again ", Toast.LENGTH_LONG).show();
                    return;
                } else {
                    uri = data.getData();
                }
            }

            break;
        }

        case 1: {
            if (requestCode == IMAGE_CAPTURE && resultCode == Activity.RESULT_OK) {
                if (data == null) {
                    Toast.makeText(getApplicationContext(), "error selecting file!, Please try again ", Toast.LENGTH_LONG).show();
                    return;
                } else {
                        uri = data.getData();
                        /* // Also I try this:
                        Bitmap photo = (Bitmap) data.getExtras().get("data");
                        uri = getImageUri(getApplicationContext(), photo); */
                }
            }
            break;
        }
    }
        super.onActivityResult(requestCode, resultCode, data);
}







public Uri getImageUri(Context inContext, Bitmap inImage) {
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
    String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
    return Uri.parse(path);
}
    private boolean hasStoragePermission(int requestCode) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED &&
                checkSelfPermission(Manifest.permission.CAMERA)
                        != PackageManager.PERMISSION_GRANTED) {
            requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, requestCode);
            requestPermissions(new String[]{Manifest.permission.CAMERA},
                    requestCode);
            return false;
        } else {
            return true;
        }
    } else {
        return true;
    }
}
  private boolean hasStoragePermission(int requestCode) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED &&
                checkSelfPermission(Manifest.permission.CAMERA)
                        != PackageManager.PERMISSION_GRANTED) {
            requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, requestCode);
            requestPermissions(new String[]{Manifest.permission.CAMERA},
                    requestCode);
            return false;
        } else {
            return true;
        }
    } else {
        return true;
    }
}
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />

我错过了什么?谢谢!

共有1个答案

许永年
2023-03-14

对于Android 8.0或更高版本,您必须添加创建文件提供程序才能访问照片。添加文件提供程序

在清单文件的应用程序标签下添加以下标签。

<provider
                android:name="android.support.v4.content.FileProvider"
                android:authorities="com.example.provider"
                android:exported="false"
                android:grantUriPermissions="true"
                tools:replace="android:authorities">
                <meta-data
                    android:name="android.support.FILE_PROVIDER_PATHS"
                    android:resource="@xml/provider_paths"
                    tools:replace="android:resource" />

</provider>

在xml文件夹中创建provider_paths.xml

<?xml version="1.0" encoding="utf-8"?>
<paths>
    <external-path
        name="external_files"
        path="." />
</paths>

意图捕捉图像

Intent takePicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    // Create the File where the photo should go
                    File photoFile = null;
                    try {
                        photoFile = createImageFile();
                    } catch (IOException ex) {
                        // Error occurred while creating the File

                    }
                    // Continue only if the File was successfully created
                    if (photoFile != null) {
                        if ((Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT)) {
                            photoURI = FileProvider.getUriForFile(getContext(),
                                    "com.example.provider",
                                    photoFile);
                            //FAApplication.setPhotoUri(photoURI);
                        } else {
                            photoURI = Uri.fromFile(photoFile);
                        }

                        takePicture.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
                        startActivityForResult(takePicture, 101);

和在 onActivity 结果

if (requestCode == 101) {
                    Uri contentUri = FileProvider.getUriForFile(getContext(), "com.example.provider", new File(mCurrentPhotoPath)); //You wll get the proper image uri here.
                }

createImageFile()

private File createImageFile() throws IOException {
        // Create an image file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);


        /*File file = new File(getContext().getExternalFilesDir(Environment.DIRECTORY_PICTURES)
                + File.separator
                + imageFileName);
        if (file.getParentFile().exists() || file.getParentFile().mkdirs()) {
            mCurrentPhotoPath = file.getAbsolutePath();
        }*/


        File file = File.createTempFile(
                imageFileName,   //prefix
                ".jpg",          //suffix
                storageDir       //directory
        );

        // Save a file: path for use with ACTION_VIEW intents

        return file;
    }
 类似资料:
  • 在Android牛轧糖及以上版本中,从相机意图捕获图像的方法被改变了,下面的代码对我来说很好。 内容://com.example.demo.provider/external_files/camera/img_201712130_015646.jpg

  • 问题内容: 我启动了一项活动以从相机捕获图片: 您能告诉我如何获取拍摄图片的URI吗? 问题答案: 要获取刚从相机拍摄的图像,请执行以下操作

  • 我有以下代码,它要求用户从照片应用程序中选择一个图像或通过相机应用程序捕捉一个图像: 和OnActivityResult的代码:

  • 问题内容: 如何连续从摄像头捕获图像? 我想尝试对象识别(也许使用Java Media Framework)。 我当时正在考虑创建两个线程 一个线程: 节点1:捕获实时图像 节点2:将图片另存为“ 1.jpg” 节点3:等待5秒 节点4:重复… 其他线程: 节点1:等到捕获图像 节点2:使用“ 1.jpg”获取每个像素的颜色 节点3:将数据保存在数组中 节点4:重复… 问题答案: 此JavaCV实

  • 我想从接收正常文件路径,如下所示: 这个文件也存在,但我不能得到它。我在这里看到了一些建议获得路径的问题,如下所示: 但此方法返回以下异常: 因此,我在这里收到的: 如何将文件转换为字符串:

  • 我下面有一个方法: