URI Location to save a photo

前端 未结 3 416
梦毁少年i
梦毁少年i 2021-01-29 07:14

How to create URI Location to save a photo captured by a camera?

I created a intent to start camera to captured photo. I want to pass URI location through the EXTRA_OUTP

3条回答
  •  说谎
    说谎 (楼主)
    2021-01-29 08:21

    I created PictureUtils class for capture image from camera and Gallery. Here is below code

    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;
            }
        }
    }
    

    Now you can call camera intent using below way on click of any button.

    Global Declaration : Uri fileUri;

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

    You can handel the result in onActivityResult method using below way.

    @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();
                    }
                }
            }
        }
    

    For Display image in imageview

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

    or you can simply set image bitmap in imageview without using glide.

    I handeled below case in above example.

    • If version is >= N, the I am using FileProvider.getUriForFile and Uri.fromFile for lower version.
    • Display right rotation of Image instead of Display image after rotate.

    Add below code in AndroidManefest.xml file under application tag for file provider

    
    
    
                
            
    
    

    Create filepaths.xml file under xml resource directory

    
    
        
    
    

    Make sure you popup and handel runtime permission for Camera and Write Internal Storage permission before call camera intent.

提交回复
热议问题