保存照片的URI位置

时间:2019-06-12 04:18:33

标签: android

如何创建URI位置来保存相机拍摄的照片?

我创建了一个意图,以启动相机拍摄照片。我想通过EXTRA_OUTPUT额外传递URI位置。如何生成这样的URI。

3 个答案:

答案 0 :(得分:1)

我创建了PictureUtils类,用于从相机和图库中捕获图像。这是下面的代码

PictureUtils.java

public class PictureUtils {

    private static String fileName;
    public Activity activity;

    public PictureUtils(Activity activity){
        this.activity = activity;
    }

    public Uri openCameraIntent(int requestCode) {
        Uri file = null;
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            file = FileProvider.getUriForFile(activity, BuildConfig.APPLICATION_ID + ".provider", getOutputMediaFile());
        } else {
            file = Uri.fromFile(getOutputMediaFile());
        }

        intent.putExtra(MediaStore.EXTRA_OUTPUT, file);
        activity.startActivityForResult(intent, requestCode);

        return file;
    }

    public void openGalleryIntent(int requestCode) {
        Intent pickPhoto = new Intent(Intent.ACTION_PICK,
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        pickPhoto.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        activity.startActivityForResult(pickPhoto, requestCode);
    }

    private static File getOutputMediaFile() {

        File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/RVRB");

        if (!mediaStorageDir.exists()) {
            if (!mediaStorageDir.mkdirs()) {
                return null;
            }
        }
        String timeStamp = String.valueOf(System.currentTimeMillis());
        fileName = timeStamp + ".jpg";

        return new File(mediaStorageDir.getAbsolutePath() + File.separator + fileName);
    }

    public ImagesData resultFromCamera(Intent data) {

        File imageFile = null;
        float rotationDegree = 0;
        String exifOrientation;
        ExifInterface exif = null;

        Bitmap rotatedBitmap = null;

        File storageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/RVRB");
        boolean success = true;
        if (!storageDir.exists()) {
            success = storageDir.mkdirs();
        }
        if (success) {
            imageFile = new File(storageDir, fileName);
        }

        try {
            exif = new ExifInterface(imageFile.getAbsolutePath());
            exifOrientation = exif.getAttribute(ExifInterface.TAG_ORIENTATION);

            if (Integer.parseInt(exifOrientation) >= 0 && Integer.parseInt(exifOrientation) <= 1) {
                rotationDegree = 0;
            } else if (Integer.parseInt(exifOrientation) >= 2 && Integer.parseInt(exifOrientation) <= 4) {
                rotationDegree = 180;
            } else if (Integer.parseInt(exifOrientation) >= 7 && Integer.parseInt(exifOrientation) >= 8) {
                rotationDegree = 270;
            } else {
                rotationDegree = 90;
            }

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            Bitmap thumbnail = null;
            if (data != null && data.getData() != null) {
                try {
                    thumbnail = MediaStore.Images.Media.getBitmap(activity.getContentResolver(), data.getData());
                    Matrix matrix = new Matrix();
                    matrix.postRotate(rotationDegree);
                    Bitmap scaledBitmap = Bitmap.createScaledBitmap(thumbnail, thumbnail.getWidth(), thumbnail.getHeight(), true);
                    rotatedBitmap = Bitmap.createBitmap(scaledBitmap, 0, 0, scaledBitmap.getWidth(), scaledBitmap.getHeight(), matrix, true);

                    if (imageFile != null) {
                        OutputStream fOut = new FileOutputStream(imageFile);
                        rotatedBitmap.compress(Bitmap.CompressFormat.JPEG, 70, fOut);
                        fOut.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                try {

                    thumbnail = MediaStore.Images.Media.getBitmap(activity.getContentResolver(), Uri.fromFile(imageFile));

                    Matrix matrix = new Matrix();
                    matrix.postRotate(rotationDegree);
                    Bitmap scaledBitmap = Bitmap.createScaledBitmap(thumbnail, thumbnail.getWidth(), thumbnail.getHeight(), true);
                    rotatedBitmap = Bitmap.createBitmap(scaledBitmap, 0, 0, scaledBitmap.getWidth(), scaledBitmap.getHeight(), matrix, true);

                    if (imageFile != null) {
                        OutputStream fOut = new FileOutputStream(imageFile);
                        rotatedBitmap.compress(Bitmap.CompressFormat.JPEG, 70, fOut);
                        fOut.close();
                    }

                } catch (IOException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } else {
            try {
                Bitmap bitmap = null;
                imageFile = new File(storageDir, fileName);

                bitmap = MediaStore.Images.Media.getBitmap(activity.getContentResolver(), Uri.fromFile(imageFile));

                if (bitmap != null && (bitmap.getHeight() < bitmap.getWidth())) {
                    Matrix matrix = new Matrix();
                    matrix.postRotate(rotationDegree);
                    Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmap, bitmap.getWidth(), bitmap.getHeight(), true);
                    rotatedBitmap = Bitmap.createBitmap(scaledBitmap, 0, 0, scaledBitmap.getWidth(), scaledBitmap.getHeight(), matrix, true);

                    if (imageFile != null) {
                        OutputStream fOut = new FileOutputStream(imageFile);
                        rotatedBitmap.compress(Bitmap.CompressFormat.JPEG, 70, fOut);
                        fOut.close();
                    }
                } else {
                    rotatedBitmap = bitmap;
                }

            } catch (IOException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return new ImagesData(imageFile, rotatedBitmap);
    }

    public ImagesData imageFromGallery(Intent data) {

        File imageFile = null;
        float rotationDegree = 0;
        Bitmap rotatedBitmap = null;
        try {
            Bitmap bm = null;
            Uri selectedImage = null;
            if (data != null && data.getData() != null) {
                try {
                    selectedImage = data.getData();
                    bm = MediaStore.Images.Media.getBitmap(activity.getContentResolver(), selectedImage);

                } catch (IOException e) {
                    e.printStackTrace();
                }
            } else {
                try {
                    bm = (Bitmap) data.getExtras().get("data");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            String timeStamp = String.valueOf(System.currentTimeMillis());
            String fileName = timeStamp + ".jpg";

            File storageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/RVRB");
            boolean success = true;
            if (!storageDir.exists()) {
                success = storageDir.mkdirs();
            }
            if (success) {
                imageFile = new File(storageDir, fileName);
            }

            rotationDegree = getRotationFromURI(selectedImage, activity);

            Matrix matrix = new Matrix();
            matrix.postRotate(rotationDegree);
            Bitmap scaledBitmap = Bitmap.createScaledBitmap(bm, bm.getWidth(), bm.getHeight(), true);
            rotatedBitmap = Bitmap.createBitmap(scaledBitmap, 0, 0, scaledBitmap.getWidth(), scaledBitmap.getHeight(), matrix, true);

            if (imageFile != null) {
                OutputStream fOut = new FileOutputStream(imageFile);
                rotatedBitmap.compress(Bitmap.CompressFormat.JPEG, 70, fOut);
                fOut.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ImagesData(imageFile, rotatedBitmap);
    }

    private int getRotationFromURI(Uri contentUri, Context mContext) {
        Cursor cursor = null;
        try {
            String[] proj = new String[]{MediaStore.Images.ImageColumns.ORIENTATION};
            cursor = mContext.getContentResolver().query(contentUri, proj, null, null, null);
            assert cursor != null;
            cursor.moveToFirst();
            return cursor.getInt(0);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
        return 0;
    }

    public class ImagesData {

        File imageFile = null;
        Bitmap bitmap = null;

        private ImagesData(File imageFile, Bitmap bitmap) {
            this.imageFile = imageFile;
            this.bitmap = bitmap;
        }

        public File getImageFile() {
            return imageFile;
        }

        public void setImageFile(File imageFile) {
            this.imageFile = imageFile;
        }

        public Bitmap getBitmap() {
            return bitmap;
        }

        public void setBitmap(Bitmap bitmap) {
            this.bitmap = bitmap;
        }
    }
}

现在,只要按一下任何按钮,就可以使用以下方法调用相机意图。

全球宣言:Uri fileUri;

PictureUtils images = new PictureUtils(ArtistAddEditMembers.this);
fileUri = images.openCameraIntent(REQUEST_OPEN_CAMERA);

您可以使用以下方法以onActivityResult方法处理结果。

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

        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == REQUEST_OPEN_CAMERA) {
                try {
                    PictureUtils images = new PictureUtils(ArtistAddEditMembers.this);
                    PictureUtils.ImagesData imagesData = images.resultFromCamera(data);

                    imageFile = imagesData.getImageFile();
                    finalBitmap = imagesData.getBitmap();

                    displayImagePreview(finalBitmap);

                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else if (requestCode == REQUEST_OPEN_GALLERY) {
                try {

                    PictureUtils images = new PictureUtils(ArtistAddEditMembers.this);
                    PictureUtils.ImagesData imagesData = images.imageFromGallery(data);

                    imageFile = imagesData.getImageFile();
                    finalBitmap = imagesData.getBitmap();

                    displayImagePreview(finalBitmap);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

对于在imageview中显示图像

public void displayImagePreview(Bitmap bitmap) {
        Glide.with(mContext).load(bitmap).into(ivUserProfile);
    }

或者您可以简单地在imageview中设置图像位图,而无需使用glide。

我在上面的示例中处理了以下情况。

  • 如果版本>> N,则我将FileProvider.getUriForFileUri.fromFile用于较低版本。
  • 显示图像的右旋转,而不是旋转后显示图像。

在AndroidManefest.xml文件中的文件提供商的应用程序标签下添加以下代码

<application
......>

<provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="${applicationId}.provider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/filepaths" />
        </provider>
</application>

在xml资源目录下创建filepaths.xml文件

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

在调用摄像机意图之前,请确保您已弹出并处理“摄像机”的运行时权限并“写入内部存储”权限。

答案 1 :(得分:0)

使用此代码生成文件并将其调用到相机意图中

    File imagefile = null;
    try {
        imagefile = createImageFile();
    } catch (IOException ex) {
        // Error while creating the File
        Log.i(TAG, "IOException");
    }

    if (imagefile != null) {
        cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
        startActivityForResult(cameraIntent, REQUEST_IMAGE_CAPTURE);
    }

这是生成Imagefile的代码

private File createImageFile() throws IOException {

    String imageFileName = "JPEG_" + System.currentTimeMillis() + "_";
    File storageDir = Environment.getExternalStoragePublicDirectory(
            Environment.DIRECTORY_PICTURES);
    File image = File.createTempFile(
            imageFileName,  // prefix
            ".jpg",         // suffix
            storageDir      // directory
    );
    return image;
}

答案 2 :(得分:0)

private void SaveImage(Bitmap finalBitmap) {

String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/saved_images");    
myDir.mkdirs();
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "Image-"+ n +".jpg";
File file = new File (myDir, fname);
if (file.exists ()) file.delete (); 
try {
       FileOutputStream out = new FileOutputStream(file);
       finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
       out.flush();
       out.close();

} catch (Exception e) {
       e.printStackTrace();
}

}