通过Intent捕获图像后存储全尺寸图像的内容URI

时间:2018-06-29 16:58:58

标签: android kotlin uri android-file android-fileprovider

遵循docs for taking photos之后,我想知道如何将完整尺寸的图像(根据其内容URI)存储到公共外部存储目录中。

我首先在将返回值分配给字段时检索照片路径:

currentPhotoPath = intentToCamera(RC_TAKE_PICTURE)

这是intentToCamera():

protected fun intentToCamera(requestCode: Int) : String? {
        var photoPath: String? = null

        (activity as? BaseActivity)?.let {
            try {
                val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
                if (intent.resolveActivity(it.packageManager) != null) {
                    val imageFile: File? = createImageFile()
                    photoPath = imageFile?.absolutePath ?: return@let
                    startActivityForResult(intent, requestCode)
                }
            } catch (ioException: IOException) {
                TeamBuildrApp.logThrowable(ioException)
                showErrorDialog(getString(R.string.err_generic_msg))
            }
        }

        return photoPath
}

这是createImageFile():

@Nullable
public File createImageFile() {
        File imageFile = null;

        String timeStamp = FILE_DATE_FORMAT.format(new Date());
        String imageFileName = String.format("JPEG_%s_", timeStamp);
        String suffix = ".jpg";
        File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        try {
            imageFile = File.createTempFile(
                    imageFileName,
                    suffix,
                    storageDir
            );
        } catch (Exception ex) {
            TeamBuildrApp.logThrowable(ex);
            showErrorDialog(getString(R.string.err_generic_msg));
        }

        return imageFile;
}

这是onActivityResult():

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        when (requestCode) {
            RC_TAKE_PICTURE -> {
                if (Activity.RESULT_OK == resultCode && !currentPhotoPath.isNullOrBlank()) {
                    val imageFile = addPhotoToGallery(currentPhotoPath)
                    uploadImage(imageFile) // API call
                }
            }
        }
}

这是addPhotoToGallery():

@Nullable
public File addPhotoToGallery(@Nullable String photoPath) {
        File imageFile = null;

        if (photoPath != null && !photoPath.isEmpty()) {
            Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
            File file = new File(photoPath);
            String applicationId = getPackageName();
            Uri contentUri = FileProvider.getUriForFile(this, String.format("%s.fileprovider", applicationId), file);
            imageFile = ViewUtils.createTempJpgFile(this, contentUri, 80);
            mediaScanIntent.setData(contentUri);
            sendBroadcast(mediaScanIntent);
        }

        return imageFile;
}

最后,这是createTempJpgFile():

@Nullable
public static File createTempJpgFile(Context context, @Nullable Uri uri, int quality) {
        if (uri != null) {
            String timeStamp = String.valueOf(new Date().getTime());
            String tmpFileName = String.format("JPEG_%s_", timeStamp);
            String suffix = ".jpg";
            File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);

            try {
                InputStream inputStream = context.getContentResolver().openInputStream(uri);

                try {
                    BitmapFactory.Options options = new BitmapFactory.Options();
                    options.inSampleSize = 1;
                    Bitmap bitmap = BitmapFactory.decodeStream(inputStream, null, options);

                    File tmpFile = File.createTempFile(
                            tmpFileName,
                            suffix,
                            storageDir
                    );

                    FileOutputStream fileOutStream = new FileOutputStream(tmpFile);
                    bitmap.compress(Bitmap.CompressFormat.JPEG, quality, fileOutStream);
                    fileOutStream.close();

                    return tmpFile;
                } catch (Exception ex) {
                    TeamBuildrApp.logThrowable(ex);

                    return null;
                } finally {
                    inputStream.close();
                }
            } catch (Exception ex) {
                TeamBuildrApp.logThrowable(ex);
            }
        }

        return null;
}

...并且使用我的内容URI(content://com.sampleapp.android.beta.fileprovider/my_images_dev/JPEG_20180628_110049_2688674172325070529.jpg)打开流,该位图始终为空-应用抛出{ 1}}。{p>

哦,我正在使用Pixel 2(使用Google Photos应用作为存储目录)来测试btw

0 个答案:

没有答案