使用相机意图获取Android中捕获图像的路径

drkbr07n  于 2023-03-11  发布在  Android
关注(0)|答案(6)|浏览(130)

我一直在尝试获取捕获的图像的路径,以便删除图像。在StackOverflow上找到了许多答案,但没有一个对我有效。我得到了以下答案:

private String getLastImagePath() {
    final String[] imageColumns = { MediaStore.Images.Media._ID,
            MediaStore.Images.Media.DATA };
    final String imageOrderBy = MediaStore.Images.Media._ID + " DESC";
    Cursor imageCursor = POS.this.getContentResolver().query(
            MediaStore.Images.Media.EXTERNAL_CONTENT_URI, imageColumns,
            null, null, imageOrderBy);
    if (imageCursor.moveToFirst()) {
        // int id = imageCursor.getInt(imageCursor
        // .getColumnIndex(MediaStore.Images.Media._ID));
        String fullPath = imageCursor.getString(imageCursor
                .getColumnIndex(MediaStore.Images.Media.DATA));
        return fullPath;
    } else {
        return "";
    }
}

此代码在三星标签,但不工作在联想标签和i球标签。所以,有人能帮我找到另一个解决方案来做同样的事吗?任何帮助将不胜感激。谢谢。
这是我的活动结果:

if (requestCode == CmsInter.CAMERA_REQUEST && resultCode == RESULT_OK) {
    //Bitmap photo = null;
    //photo = (Bitmap) data.getExtras().get("data");

    String txt = "";
    if (im != null) {
        String result = "";
        //im.setImageBitmap(photo);
        im.setTag("2");
        int index = im.getId();
        String path = getLastImagePath();
        try {
            bitmap1 = BitmapFactory.decodeFile(path, options);
            bitmap = Bitmap.createScaledBitmap(bitmap1, 512, 400, false);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
            byte[] bytData = baos.toByteArray();
            try {
                baos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            result = Base64.encode(bytData);
            bytData = null;
        } catch (OutOfMemoryError ooM) {
            System.out.println("OutOfMemory Exception----->" + ooM);
            bitmap1.recycle();
            bitmap.recycle();
        } finally {
            bitmap1.recycle();
            bitmap.recycle();
        }
    }
}
wmtdaxz3

wmtdaxz31#

像这样试试
如下所示传递摄像头意图

Intent intent = new Intent(this);
    startActivityForResult(intent, REQ_CAMERA_IMAGE);

捕获图像后,写入OnActivityResult,如以下代码所示,这些代码复制自堆栈溢出答案在Android上获取图像的文件路径-

protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
        if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
            Bitmap photo = (Bitmap) data.getExtras().get("data"); 
            imageView.setImageBitmap(photo);
            knop.setVisibility(Button.VISIBLE);
    
    
            // CALL THIS METHOD TO GET THE URI FROM THE BITMAP
            Uri tempUri = getImageUri(getApplicationContext(), photo);
    
            // CALL THIS METHOD TO GET THE ACTUAL PATH
            File finalFile = new File(getRealPathFromURI(tempUri));
    
            System.out.println(mImageCaptureUri);
        }  
    }
    
    public Uri getImageUri(Context inContext, Bitmap inImage) {
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
        String path = Images.Media.insertImage(inContext.getContentResolver(), inImage,
"Title", null);
        return Uri.parse(path);
    }
    
    public String getRealPathFromURI(Uri uri) {
        String path = "";
        if (getContentResolver() != null) {
            Cursor cursor = getContentResolver().query(uri, null, null, null, null);
            if (cursor != null) {
                cursor.moveToFirst();
                int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
                path = cursor.getString(idx);
                cursor.close();
            }
        }
        return path;
    } ```

检查日志。

编辑:

很多人都在问如何不获取缩略图,你需要为getImageUri方法添加以下代码:

public Uri getImageUri(Context inContext, Bitmap inImage) {
        Bitmap OutImage = Bitmap.createScaledBitmap(inImage, 1000, 1000,true);
        String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), OutImage, "Title", null);
        return Uri.parse(path);
    }

另一种方法是压缩文件。您可以通过更改数字1000,1000来调整大小

g6ll5ycj

g6ll5ycj2#

有一个解决方案来创建文件(在外部缓存目录或其他任何地方),并把这个文件的URI作为输出额外的相机意图-这将定义路径所采取的图片将被存储。
下面是一个例子:

File file;
Uri fileUri;
final int RC_TAKE_PHOTO = 1;

    private void takePhoto() {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        file = new File(getActivity().getExternalCacheDir(), 
                String.valueOf(System.currentTimeMillis()) + ".jpg");
        fileUri = Uri.fromFile(file);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
        getActivity().startActivityForResult(intent, RC_TAKE_PHOTO);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == RC_TAKE_PHOTO && resultCode == RESULT_OK) {

                //do whatever you need with taken photo using file or fileUri

            }
        }
    }

然后,如果不再需要该文件,可以使用file.delete();将其删除
顺便说一句,当用户从应用程序设置中清除应用程序的缓存时,缓存目录中的文件将被删除。

chhqkbe1

chhqkbe13#

尝试使用此方法获取摄像头捕获的original图像的路径。

public String getOriginalImagePath() {
        String[] projection = { MediaStore.Images.Media.DATA };
        Cursor cursor = getActivity().managedQuery(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                projection, null, null, null);
        int column_index_data = cursor
                .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToLast();

        return cursor.getString(column_index_data);
    }

此方法将返回相机捕获的最后一张图像的路径。因此此路径将是原始图像,而不是缩略图位图。

yqlxgs2m

yqlxgs2m4#

在这里我更新了Kotlin的示例代码。请注意,牛轧糖及以上版本Uri.fromFile(file)不工作,它崩溃的应用程序,需要实现FileProvider这是最安全的方式发送文件的意图。实现这一点,请参阅此answer或此article

private fun takePhotoFromCamera() {
        val isDeviceSupportCamera: Boolean = this.packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA)
        if (isDeviceSupportCamera) {
            val takePictureIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)

            if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
                file = File(getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS + "/attachments")!!.path,
                        System.currentTimeMillis().toString() + ".jpg")
//            fileUri = Uri.fromFile(file)
                fileUri = FileProvider.getUriForFile(this, this.applicationContext.packageName + ".provider", file!!)
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri)
                if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.LOLLIPOP) {
                    takePictureIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
                }
                startActivityForResult(takePictureIntent, Constants.REQUEST_CODE_IMAGE_CAPTURE)
            }

        } else {
            Toast.makeText(this, this.getString(R.string.camera_not_supported), Toast.LENGTH_SHORT).show()
        }
    }

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK) {
             if(requestCode == Constants.REQUEST_CODE_IMAGE_CAPTURE) {
                realPath = file?.path
                 //do what ever you want to do
            }
    }
}
km0tfn4u

km0tfn4u6#

试试这个

String[] projection = { MediaStore.Images.Media.DATA };
            @SuppressWarnings("deprecation")
            Cursor cursor = managedQuery(mCapturedImageURI, projection,
                    null, null, null);
            int column_index_data = cursor
                    .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            image_path = cursor.getString(column_index_data);
            Log.e("path of image from CAMERA......******************.........",
                    image_path + "");

用于捕获图像:

String fileName = "temp.jpg";
    ContentValues values = new ContentValues();
    values.put(MediaStore.Images.Media.TITLE, fileName);
    mCapturedImageURI = getContentResolver().insert(
            MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);

    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    intent.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);
    values.clear();

相关问题