-2

I am trying to load an image from a file chooser into an ImageView.

In tutorial i see it like this:

try {
        Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), mImageUri);
        mImageView.setImageBitmap(bitmap);
    } catch (IOException e) {
        e.printStackTrace();
    }

However, I just tried a simple

mImageView.setImageUri(mImageUri)

instead and it works just as well. Am I missing something here? Why are these tutorials usin such a big amount of code if it works with 1 line?

Florian Walther
  • 6,237
  • 5
  • 46
  • 104

1 Answers1

2

From pierrotlefou answer on Android - ImageView: setImageBitmap VS setImageDrawable


ImageView has 4 APIs to specify the image. Which one to use? What is the difference?

  1. setImageDrawable(Drawable drawable)
  2. setImageBitmap(Bitmap bm)
  3. setImageResource(int resId)
  4. setImageURI(URI uri)

ImageView, by the name, is used to display an image. But what is a image? A Bitmap is-a image, not hard to understand and we use setImageBitmap for that purpose. However, internally, the ImageView has-a Drawable but not a Bitmap and that is what setImageDrawable for. When you call setImageBitmap, internally, first the bitmap will be wrapped to BitmapDrawable, which IS-A Drawable, and then call setImageDrawable.

Here is the code.

public void setImageBitmap(Bitmap bm) {
    setImageDrawable(new BitmapDrawable(mContext.getResources(), bm));
}

So, what about the 3 and 4 API?

You should already know that that are bunches of ways to create a bitmap: from a file path, from an input stream, from the Uri, or from the resource file.

BitmapFactory.decodeFile(String pathName)
BitmapFactory.decodeStream(Inputstream)
BitmapFactory.decodeResource(Resource res, int id)
BitmapFactory.decodeByteArray(byte[] data)

Aware of this, it is easy to understand setImageResource/setImageUri is just same as setImageBitmap.

To sum up, setImageDrawable is the primitive function other APIs rely on. The other 3 are just helper methods making you write less code.

In addition, it is very important to keep in mind that ImageView actually has-a Drawable, which not necessarily to be a BitmapDrawable! You could set any Drawable to the Image view.

Besides setting the Drawable through Java API, you could also using XML attribution to set the source Drawable for ImageView. See example below. Note that the shape could be either an image file (.png, .jpg, .bmp) or xml file.

  • Comments are not for extended discussion; this conversation has been [moved to chat](http://chat.stackoverflow.com/rooms/162280/discussion-on-answer-by-ricky-notaro-garcia-difference-between-setimagebitmap-an). – Bhargav Rao Jan 01 '18 at 12:47