Read/Write Images

To read Image from Gallery-

I worked on ImageButton to get Image from gallery:

private void uploadImageClicked() {

    new Thread(new Runnable() {
        Intent intent = new Intent(Intent.ACTION_PICK);
        public void run() {
            openGallery(intent);  
      }
    }).start();
}

private void openGallery(Intent intent) {
    intent.setType("image/*");  
    startActivityForResult(intent, 0);
}

The above piece of code open the Gallery to select the Image as desired. Here, we create an INTENT in order to access Gallery and hence, set the path as "image/*" and call startActivityForResult(intent, 0) so as to start the activity that utilize intent.

To write Image from Gallery-

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (resultCode == RESULT_OK && null != data) {
            uploadImageButton.setBackgroundResource(0);
            Uri selectedImage = data.getData();
            String[] filePathColumn = {MediaStore.Images.Media.DATA};

            Glide.with(this)
                    .load(selectedImage)
                    .centerCrop()            
                    .into(uploadImageButton);
            Toast.makeText(this, "Image Uploaded", Toast.LENGTH_SHORT).show();
        } 
    }

The above code uses GLIDE to set the retrieved image into the ImageButton.
Below is the detail - 
  • .load() - loads the image
  • .centreCrop()/.fitCentre() - aligns the image on ImageButton
  • .into(target) - Set the image on the target

Comments

Popular posts from this blog

@Overrride annotation introduced in Java1.5

Liskov Substitution Principle (LSP)

Marie Choco Lava