X

Fetch image form Camera to ImageView || Camera Intent

 

Want to fetch a image from camera and set it to the image view using intent in fragment

 

First add permission in your manifest file

 

<uses-permission android:name="android.permission.CAMERA"/>

 

then setOnClickListener for your image view

 

imageView.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        int permissionCheck = ContextCompat.checkSelfPermission(getActivity(),
              Manifest.permission.CAMERA);

        if (permissionCheck == PackageManager.PERMISSION_GRANTED) {
            pickImage();
        } else {
            ActivityCompat.requestPermissions(getActivity(),
                    new String[]{Manifest.permission.CAMERA},
                    2000);
        }
    }


});

 

choose the intent properly to open camera and click image and get back it to the fragment

 

private void pickImage() {
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    startActivityForResult(intent,
            1000);
}

 

and finally onActivityResult make sure you set it properly you can also use image loading library for more efficiency.

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    //super method removed
    if (resultCode == RESULT_OK) {
        if (resultCode == Activity.RESULT_OK) {

            Bitmap bmp = (Bitmap) data.getExtras().get("data");
            ByteArrayOutputStream stream = new ByteArrayOutputStream();

            bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
            byte[] byteArray = stream.toByteArray();

            // convert byte array to Bitmap

            Bitmap bitmap = BitmapFactory.decodeByteArray(byteArray, 0,
                    byteArray.length);

            imageView.setImageBitmap(bitmap);

        }
    }
}

 

 

abhishek:
Related Post

This website uses cookies.