Search code examples
androidandroid-imageviewandroid-gallery

import an image from gallery and set it to an imageview


I wanted to get an image imported from the gallery and set it to an imageview. I was able to select the image from the gallery but it ain't showing up in my imageview. I have tried some of the related questions but wasn't able to get the result.

Questions that I have tried:

Picture from gallery to an imageview

Picking image from gallery and set to imageview

My code:

 private void pickFromGallery() {
    //Create an Intent with action as ACTION_PICK
    Intent intent=new Intent(Intent.ACTION_PICK);
    // Sets the type as image/*. This ensures only components of type image are selected
    intent.setType("image/*");
    //We pass an extra array with the accepted mime types. This will ensure only components with these MIME types as targeted.
    String[] mimeTypes = {"image/jpeg", "image/png"};
    intent.putExtra(Intent.EXTRA_MIME_TYPES,mimeTypes);
    // Launching the Intent
    startActivityForResult(intent,REQUEST_GET_SINGLE_FILE);
}

public void onActivityResult(int requestCode,int resultCode,Intent data){
    if (data != null && requestCode==RESULT_OK){
        Uri selectedImage=data.getData();
        thumbnailImage.setImageURI(selectedImage);
    }
}

Solution

  • I'll share what I think should help you far enough. You can refactor to meet your resources. This will help you get image from both gallery and camera. To crop images, I'd recommend a library like uCrop or edmodo cropper.

    public class MainActivity extends Activity {
    
        private int REQUEST_CAMERA = 0, SELECT_FILE = 1;
        private Button btnSelect;
        private ImageView ivImage;
        private String userChoosenTask;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
    btnSelect = (Button) findViewById(R.id.btnSelectPhoto);
            btnSelect.setOnClickListener(new OnClickListener() {
    
                @Override
                public void onClick(View v) {
                    selectImage();
                }
            });
            ivImage = (ImageView) findViewById(R.id.ivImage);
        }
    
        @Override
        public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
            switch (requestCode) {
                case Utils.MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE:
                    if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                        if(userChoosenTask.equals("Take Photo"))
                            cameraIntent();
                        else if(userChoosenTask.equals("Choose from Library"))
                            galleryIntent();
                    } else {
                        //code for deny
                    }
                    break;
            }
        }
    
        private void selectImage() {
            final CharSequence[] items = { "Take Photo", "Choose from Library",
                    "Cancel" };
    
            AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
            builder.setTitle("Add Photo!");
            builder.setItems(items, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int item) {
                    boolean result=Utils.checkPermission(MainActivity.this);
    
                    if (items[item].equals("Take Photo")) {
                        userChoosenTask ="Take Photo";
                        if(result)
                            cameraIntent();
    
                    } else if (items[item].equals("Choose from Library")) {
                        userChoosenTask ="Choose from Library";
                        if(result)
                            galleryIntent();
    
                    } else if (items[item].equals("Cancel")) {
                        dialog.dismiss();
                    }
                }
            });
            builder.show();
        }
    
        private void galleryIntent()
        {
            Intent intent = new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);//
            startActivityForResult(Intent.createChooser(intent, "Select File"),SELECT_FILE);
        }
    
        private void cameraIntent()
        {
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            startActivityForResult(intent, REQUEST_CAMERA);
        }
    
        @Override
        public void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
    
            if (resultCode == Activity.RESULT_OK) {
                if (requestCode == SELECT_FILE)
                    onSelectFromGalleryResult(data);
                else if (requestCode == REQUEST_CAMERA)
                    onCaptureImageResult(data);
            }
        }
    
        private void onCaptureImageResult(Intent data) {
            Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
            ByteArrayOutputStream bytes = new ByteArrayOutputStream();
            thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
    
            File destination = new File(Environment.getExternalStorageDirectory(),
                    System.currentTimeMillis() + ".jpg");
    
            FileOutputStream fo;
            try {
                destination.createNewFile();
                fo = new FileOutputStream(destination);
                fo.write(bytes.toByteArray());
                fo.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
    
            ivImage.setImageBitmap(thumbnail);
        }
    
        @SuppressWarnings("deprecation")
        private void onSelectFromGalleryResult(Intent data) {
    
            Bitmap bm=null;
            if (data != null) {
                try {
                    bm = MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(), data.getData());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
    
            ivImage.setImageBitmap(bm);
        }
    
    }
    

    Create the Utils class

    public class Utils {
        public static final int MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE = 123;
    
        @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
        public static boolean checkPermission(final Context context)
        {
            int currentAPIVersion = Build.VERSION.SDK_INT;
            if(currentAPIVersion>=android.os.Build.VERSION_CODES.M)
            {
                if (ContextCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                    if (ActivityCompat.shouldShowRequestPermissionRationale((Activity) context, Manifest.permission.READ_EXTERNAL_STORAGE)) {
                        AlertDialog.Builder alertBuilder = new AlertDialog.Builder(context);
                        alertBuilder.setCancelable(true);
                        alertBuilder.setTitle("Permission necessary");
                        alertBuilder.setMessage("External storage permission is necessary");
                        alertBuilder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                            @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
                            public void onClick(DialogInterface dialog, int which) {
                                ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
                            }
                        });
                        AlertDialog alert = alertBuilder.create();
                        alert.show();
    
                    } else {
                        ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
                    }
                    return false;
                } else {
                    return true;
                }
            } else {
                return true;
            }
        }
    }