1

I'm new in Android and I would create app that uses camera, store image taken from camera in device and show it in gallery? Anyone have any advice on how to do it? For now I have created the activity that allows you to take pictures but I don't know how to proceed to save and show the photos taken from the camera in the gallery. Please help me, I'm very desperate. Thanks in advance to everyone.

This is my code from android documentation:

public class CamActivity extends AppCompatActivity {

    private ImageView imageView;
    private Button photoButton;
    private String currentPhotoPath;
    private File photoFile = null;

    static final int REQUEST_IMAGE_CAPTURE = 1;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_new_camera);
        imageView =  findViewById(R.id.taken_photo);
        photoButton = findViewById(R.id.btnCaptureImage);

        photoButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(checkPermissions()) {
                    dispatchTakePictureIntent();
                    galleryAddPic();
                }
            }
        });
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
            Bitmap myBitmap = BitmapFactory.decodeFile(photoFile.getAbsolutePath());
            imageView.setImageBitmap(myBitmap);
        } else  {
            Toast.makeText(this, "Cancelled", Toast.LENGTH_LONG).show();
        }
    }

    private File createImageFile() throws IOException {
        // Create an image file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        //File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        File storageDir = new File(Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_DCIM), "Camera");
        File image = File.createTempFile(
                imageFileName,  /* prefix */
                ".jpg",         /* suffix */
                storageDir      /* directory */
        );

        // Save a file: path for use with ACTION_VIEW intents
        currentPhotoPath = image.getAbsolutePath();
        return image;
    }

    private void dispatchTakePictureIntent() {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        // Ensure that there's a camera activity to handle the intent
        if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
            // Create the File where the photo should go
            try {
                photoFile = createImageFile();
            } catch (IOException ex) {
                // Error occurred while creating the File
                Toast.makeText(CamActivity.this, "error" + ex.getMessage(), Toast.LENGTH_SHORT).show();
            }
            // Continue only if the File was successfully created
            if (photoFile != null) {
                Uri photoURI = FileProvider.getUriForFile(this,
                        "com.example.myapp.fileprovider",
                        photoFile);
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
                startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
            }
        }
    }

    private void galleryAddPic() {
        Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        File f = new File(currentPhotoPath);
        Uri contentUri = Uri.fromFile(f);
        mediaScanIntent.setData(contentUri);
        this.sendBroadcast(mediaScanIntent);
    }

    private boolean checkPermissions() {
        //Check permission
        if (ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.CAMERA)
                == PackageManager.PERMISSION_GRANTED) {
            //Permission Granted
            return true;
        } else {
            //Permission not granted, ask for permission
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, REQUEST_IMAGE_CAPTURE);
            return false;
        }
    }

}


1 Answers1

1

allow camera and storage permission

public class CamActivity extends AppCompatActivity {

    private ImageView imageView;
    private Button photoButton;
    private String currentPhotoPath;
    private File photoFile = null;
    private static final String TAG = "CamActivity";
    static final int REQUEST_IMAGE_CAPTURE = 1;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        imageView = findViewById(R.id.taken_photo);
        photoButton = findViewById(R.id.btnCaptureImage);

        photoButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                captureImage();
            }
        });
    }


    @SuppressLint("QueryPermissionsNeeded")
    private void captureImage() {
        Intent pictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (pictureIntent.resolveActivity(getPackageManager()) != null) {
            startActivityForResult(pictureIntent, 100);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 100 && resultCode == RESULT_OK) {
            if (data != null && data.getExtras() != null) {
                Bitmap imageBitmap = (Bitmap) data.getExtras().get("data");
                saveImage(imageBitmap);
                imageView.setImageBitmap(imageBitmap);
            }
        }
    }

    private void saveImage(Bitmap bitmap) {
        String filename;
        Date date = new Date(0);
        @SuppressLint("SimpleDateFormat")
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        filename = sdf.format(date);

        try {
            String path = Environment.getExternalStorageDirectory().toString();
            OutputStream outputStream = null;
            File file = new File(path, "/MyImages/"+filename + ".jpg");
            File root = new File(Objects.requireNonNull(file.getParent()));
            if (file.getParent() != null && !root.isDirectory()) {
                root.mkdirs();
            }
            outputStream = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 85, outputStream);
            outputStream.flush();
            outputStream.close();
            MediaStore.Images.Media.insertImage(getContentResolver(), file.getAbsolutePath(), file.getName(), file.getName());

        } catch (Exception e) {
            Log.e(TAG, "saveImage: " + e);
            e.printStackTrace();
        }
    }
}
pankaj sharma
  • 181
  • 2
  • 12
  • Hi, first of all thanks for the reply. Anyway I tried this code but it doesn't save the image and doesn't show it in the gallery. How is it possible? – Francesco Bottiglia Jan 16 '21 at 20:19
  • @FrancescoBottiglia hello this code save your image in your mobile storage. gallery application just scan this storage and display the image or other media files – pankaj sharma Jan 16 '21 at 20:24
  • Okok however it doesn't work because nothing is saved since I can't find any folder with this name "/ MyImages /". – Francesco Bottiglia Jan 16 '21 at 21:07
  • if (file.getParent() != null && !root.isDirectory()) { root.mkdirs(); }else{ Log.e(TAG, "Folder not created "); } and check that android permission is allowed or not – pankaj sharma Jan 19 '21 at 16:07
  • Thanks but I solved it by adding a method that takes care of refreshing the gallery of the device as I could not view the photos there – Francesco Bottiglia Jan 19 '21 at 17:31