Capture Image from Camera and Display in Activity

前端 未结 16 1037
悲&欢浪女
悲&欢浪女 2020-11-21 06:43

I want to write a module where on a click of a button the camera opens and I can click and capture an image. If I don\'t like the image I can delete it and click one more i

16条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-21 07:14

    I created a dialog with the option to choose Image from gallery or camera. with a callback as

    • Uri if the image is from the gallery
    • String as a file path if the image is captured from the camera.
    • Image as File the image chosen from camera needs to be uploaded on the internet as Multipart file data

    At first we to define permission in AndroidManifest as we need to write external store while creating a file and reading images from gallery

    
    
    

    Create a file_paths xml in app/src/main/res/xml/file_paths.xml

    with path

    
    
        
    
    

    Then we need to define file provier to generate Content uri to access file stored in external storage

    
        
    
    

    Dailog Layout

    
    
    
        
    
        
    
        
    
    

    ImagePicker Dailog

    public class ImagePicker extends BottomSheetDialogFragment {
    ImagePicker.GetImage getImage;
    public ImagePicker(ImagePicker.GetImage getImage, boolean allowMultiple) {
        this.getImage = getImage;
    }
    File cameraImage;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.bottom_sheet_imagepicker, container, false);
        view.findViewById(R.id.camera).setOnClickListener(new View.OnClickListener() {@
            Override
            public void onClick(View view) {
                if(ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                    requestPermissions(new String[] {
                        Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE
                    }, 2000);
                } else {
                    captureFromCamera();
                }
            }
        });
        view.findViewById(R.id.gallery).setOnClickListener(new View.OnClickListener() {@
            Override
            public void onClick(View view) {
                if(ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                    requestPermissions(new String[] {
                        Manifest.permission.READ_EXTERNAL_STORAGE
                    }, 2000);
                } else {
                    startGallery();
                }
            }
        });
        return view;
    }
    public interface GetImage {
        void setGalleryImage(Uri imageUri);
        void setCameraImage(String filePath);
        void setImageFile(File file);
    }@
    Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == Activity.RESULT_OK) {
            if(requestCode == 1000) {
                Uri returnUri = data.getData();
                getImage.setGalleryImage(returnUri);
                Bitmap bitmapImage = null;
            }
            if(requestCode == 1002) {
                if(cameraImage != null) {
                    getImage.setImageFile(cameraImage);
                }
                getImage.setCameraImage(cameraFilePath);
            }
        }
    }
    private void startGallery() {
        Intent cameraIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        cameraIntent.setType("image/*");
        if(cameraIntent.resolveActivity(getActivity().getPackageManager()) != null) {
            startActivityForResult(cameraIntent, 1000);
        }
    }
    private String cameraFilePath;
    private File createImageFile() throws IOException {
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM), "Camera");
        File image = File.createTempFile(imageFileName, /* prefix */ ".jpg", /* suffix */ storageDir /* directory */ );
        cameraFilePath = "file://" + image.getAbsolutePath();
        cameraImage = image;
        return image;
    }
    private void captureFromCamera() {
        try {
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, FileProvider.getUriForFile(getContext(), BuildConfig.APPLICATION_ID + ".provider", createImageFile()));
            startActivityForResult(intent, 1002);
        } catch(IOException ex) {
            ex.printStackTrace();
        }
    }
    

    }

    Call in Activity or fragment like this Define ImagePicker in Fragment/Activity

    ImagePicker imagePicker;
    

    Then call dailog on click of button

          imagePicker = new ImagePicker(new ImagePicker.GetImage() {
                @Override
                public void setGalleryImage(Uri imageUri) {
    
                    Log.i("ImageURI", imageUri + "");
    
                    String[] filePathColumn = {MediaStore.Images.Media.DATA};
    
                    Cursor cursor = getContext().getContentResolver().query(imageUri, filePathColumn, null, null, null);
                    assert cursor != null;
                    cursor.moveToFirst();
    
                    int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                    mediaPath = cursor.getString(columnIndex);
                    // Set the Image in ImageView for Previewing the Media
                    imagePreview.setImageBitmap(BitmapFactory.decodeFile(mediaPath));
                    cursor.close();
    
                }
    
                @Override
                public void setCameraImage(String filePath) {
    
                    mediaPath =filePath;
                    Glide.with(getContext()).load(filePath).into(imagePreview);
    
                }
    
                @Override
                public void setImageFile(File file) {
    
                    cameraImage = file;
    
                }
            }, true);
            imagePicker.show(getActivity().getSupportFragmentManager(), imagePicker.getTag());
    

提交回复
热议问题