Android-image-cropper: Open Camera directly, instead of image chooser

Created on 29 Jan 2018  路  11Comments  路  Source: ArthurHub/Android-Image-Cropper

I want to open camera instead of opening image chooser or gallery. Please guide me in this regard.
Thank you

Most helpful comment

Hi @jjimenez0611 thanks for the reply,sorry for late response .I have solved the issue my logic is almost similar to your logic. But there is one problem that is android.os.FileUriExposedException coming to solve that i have used following code.

//This line is used for to avoid android.os.FileUriExposedException need to do further checking StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder(); StrictMode.setVmPolicy(builder.build());

All 11 comments

private fun openCamera() {
        val outputFileUri = getCaptureImageOutputUri(applicationContext)

        val captureIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)

        if (outputFileUri != null) {
            captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
        }

        startActivityForResult(captureIntent, CropImage.PICK_IMAGE_CHOOSER_REQUEST_CODE)
    }

Hi I have the same question! I need open the camera directly in Java Android.. Can you help me

@jjimenez0611 ,,i think this is ur solution. sorry if i am wrong.

public class MainActivity extends AppCompatActivity {
ImageView iv;
Bitmap bitmap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

   iv  = (ImageView)findViewById(R.id.image);

///start image import from default CAMERA
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, 0);
}

///now onActivityResult

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
    super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
        switch(requestCode) {
        case 0:
            if(resultCode == RESULT_OK){
                Uri selectedImage = imageReturnedIntent.getData();
                if(imageReturnedIntent.getData()==null){
                    bitmap = (Bitmap)imageReturnedIntent.getExtras().get("data");
                    iv.setImageBitmap(bitmap);
                }else{
                    try {
                        bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageReturnedIntent.getData());
                        iv.setImageBitmap(bitmap);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                Log.d("selectedImage: ", imageReturnedIntent.getData()+"");


            }

            break;

Thanks, I will implement this solution. I really appreciate your help.

The above solution by @Biplovkumar is not remotely close to the answer. The above 'answer' doesnt mention anything related to the CropImage library.

@jjimenez0611 your best bet so far is to open the default camera intent by parsing the uri, then on result of that start CropImage.activity().start(uri) with that uri instance.

I'm trying this and for the most part its working. But its not ideal, I would much rather like to open the Crop Intent with camera straight away, but doesnt seem like this is an option.

I've logged a ticket for this as well. (https://github.com/ArthurHub/Android-Image-Cropper/issues/510)

Also I've not seen many answers by the developer of this awesome library, which is weird, because it really is an awesome library.

It is not that weird my friend :) the developer of this awesome library has 80+ open issues and a life, and might be really busy :P so the community will help ya instead :)

Hi

I found a solution to my problem.
I open the camera normally and them onActivityResult open the crop activity on this way:

CropImage.activity(CropImage.getCaptureImageOutputUri(SiffApplication.getInstance().getComponent().getContext()))
.setGuidelines(CropImageView.Guidelines.ON)
.setFlipHorizontally(false)
.setFlipVertically(false)
.setActivityTitle(getString(R.string.location_image_capture))
.setAspectRatio(1, 1)
.start(getContext(), this);

And then get the crop image onActivityResult....

Hi

I found a solution to my problem.
I open the camera normally and them onActivityResult open the crop activity on this way:

CropImage.activity(CropImage.getCaptureImageOutputUri(SiffApplication.getInstance().getComponent().getContext()))
.setGuidelines(CropImageView.Guidelines.ON)
.setFlipHorizontally(false)
.setFlipVertically(false)
.setActivityTitle(getString(R.string.location_image_capture))
.setAspectRatio(1, 1)
.start(getContext(), this);

And then get the crop image onActivityResult....

I have Used your solution still it is not working.
Fallowing exception is coming.

Failed to load sampled bitmap: file:///storage/emulated/0/Android/data/
cache/pickImageResult.jpeg (No such file or directory)

Hi @BhargaviDeviYamanuri.. I really don't remember exactly in what OS do you need to do a FILE PROVIDERS in the manifest

<meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/file_paths">
        </meta-data>

And in the res folder do you need to have the file_paths.xml with the following information:


name="external"
path="." />
name="external_files"
path="." />
name="cache"
path="." />
name="external_cache"
path="." />
name="files"
path="." />

And then this es my code

override fun onRequestPermissionsResult(requestCode: Int, permissions: Array, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
when (requestCode) {
cameraPermissionsRequest -> {

            if (grantResults.isEmpty() || grantResults[0] != PackageManager.PERMISSION_GRANTED) {

                Log.i("log", "Permission has been denied by user")
            } else {
                takePicture()
            }
        }
    }
}

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)

    if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE && resultCode == RESULT_OK) {
        setPictureToView()
    }
}

private fun createImageFile(): File {
    // Create an image file name
    val storageDir: File? = getExternalFilesDir(Environment.DIRECTORY_PICTURES)
    return File.createTempFile(
        "JPEG_TEMPORAL_", /* prefix */
        ".jpg", /* suffix */
        storageDir /* directory */
    ).apply {
        // Save a file: path for use with ACTION_VIEW intents
        currentPhotoPath = absolutePath
    }
}

private fun takePicture() {

    Intent(MediaStore.ACTION_IMAGE_CAPTURE).also { takePictureIntent ->
        // Ensure that there's a camera activity to handle the intent
        takePictureIntent.resolveActivity(packageManager)?.also {
            // Create the File where the photo should go
            val photoFile: File? = try {
                createImageFile()
            } catch (ex: IOException) {
                // Error occurred while creating the File
                null
            }
            // Continue only if the File was successfully created
            photoFile?.also {
                val photoURI: Uri = FileProvider.getUriForFile(
                    this,
                    "com.example.TEST.fileprovider",
                    it
                )
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI)
                startActivityForResult(takePictureIntent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE)
            }
        }
    }

}

private fun setPictureToView() {
    // Get the dimensions of the View
    val targetW = 400
    val targetH = 400

    val bmOptions = BitmapFactory.Options().apply {
        // Get the dimensions of the bitmap
        inJustDecodeBounds = true
        BitmapFactory.decodeFile(currentPhotoPath, this)
        val photoW: Int = outWidth
        val photoH: Int = outHeight

        // Determine how much to scale down the image
        val scaleFactor: Int = Math.min(photoW / targetW, photoH / targetH)

        // Decode the image file into a Bitmap sized to fill the View
        inJustDecodeBounds = false
        inSampleSize = scaleFactor
    }
    BitmapFactory.decodeFile(currentPhotoPath, bmOptions)?.also { bitmap ->
        //imageView.setImageBitmap(bitmap)

        val stream = ByteArrayOutputStream()
        bitmap.compress(Bitmap.CompressFormat.JPEG, 60, stream)
        val imageInByte = stream.toByteArray()
        val houseImage = Base64.encodeToString(imageInByte, Base64.DEFAULT)

        inspectionAdapter.setPhoto(houseImage)

    }
}

Hi @jjimenez0611 thanks for the reply,sorry for late response .I have solved the issue my logic is almost similar to your logic. But there is one problem that is android.os.FileUriExposedException coming to solve that i have used following code.

//This line is used for to avoid android.os.FileUriExposedException need to do further checking StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder(); StrictMode.setVmPolicy(builder.build());

Was this page helpful?
0 / 5 - 0 ratings

Related issues

joseph-acc picture joseph-acc  路  9Comments

ghost picture ghost  路  8Comments

Transformat picture Transformat  路  5Comments

ValentinTaleb picture ValentinTaleb  路  6Comments

gilshallem picture gilshallem  路  8Comments