Amazing Facts of Android ImageView

Displays an arbitrary image, such as an icon. The ImageView class can load images from various sources (such as resources or content providers), takes care of computing its measurement from the image so that it can be used in any layout manager, and provides various display options such as scaling and tinting.
In this guide, we will take a look at how to use an ImageView, how to manipulate bitmaps and more.

Note: Please refer to this official Android’s Drawable Resource and Screen Support article for better understand of how image works in Android.

ImageView is comes with different configuration options to support different scaleTypes. scaleType options are used for scaling the bounds of an image to the bounds of this view. Below are the listed scaleType configuration properties supported.

  • CENTER : Displays the image centered in the view with no scaling
  • CENTER_CROP : Scales the image such that both the x and y dimensions are greater than or equal to the view, while maintaining the image aspect ratio; centers the image in the view
  • CENTER_INSIDE : Scales the image to fit inside the view, while maintaining the image aspect ratio. If the image is already smaller than the view, then this is the same as center
  • FIT_CENTER : Scales the image to fit inside the view, while maintaining the image aspect ratio. At least one axis will exactly match the view, and the result is centered inside the view
  • FIT_END : Same as fitCenter but aligned to the bottom right of the view
  • FIT_START : Same as fitCenter but aligned to the top left of the view
  • FIT_XY : Scales the x and y dimensions to exactly match the view size. dDoes not maintain the image aspect ratio
  • MATRIX : Scales the image using a supplied Matrix class. The matrix can be supplied using the setImageMatrix method. A Matrix class can be used to apply transformations such as rotations to an image

The default scaleType in FIT_CENTER.

Learn more XML attributes of ImageView click here.

Android ImageView Example

1- ImageView in layout xml file

Let us add a new activity layout file named activity_main.xml to your project res/layout folder. In this example, we will be creating three different ImageView for demonstration purpose. Note that the ImageView uses the images from drawable folder.

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#31352e" >
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" >
        <ImageView
            android:id="@+id/imageView1"
            android:layout_width="fill_parent"
            android:layout_height="150dp"
            android:layout_margin="5dp"
            android:src="@drawable/image1" />
        <ImageView
            android:id="@+id/imageView2"
            android:layout_width="fill_parent"
            android:layout_height="150dp"
            android:layout_margin="5dp"
            android:background="#fff"
            android:padding="3dp"
            android:scaleType="fitXY"
            android:src="@drawable/image2" />
        <ImageView
            android:id="@+id/imageView3"
            android:layout_width="fill_parent"
            android:layout_height="200dp"
            android:layout_margin="5dp"
            android:background="#fff"
            android:paddingBottom="50dp"
            android:paddingLeft="3dp"
            android:paddingRight="3dp"
            android:paddingTop="3dp"
            android:scaleType="fitXY"
            android:src="@drawable/image2" />
    </LinearLayout>
</ScrollView>

2- Using ImageView from Activity

ImageView imageView = (ImageView) findViewById(R.id.imageView1);
imageView.setImageResource(R.drawable.image1);

3- Getting Image URI

A- From camera :

Uri picUri;
try {
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    String imageFilePath = Environment.getExternalStorageDirectory().getAbsolutePath()
            + "/DCIM/Camera/CEDU_"+timeStamp+".jpg";
    File imageFile = new File(imageFilePath);
    picUri = Uri.fromFile(imageFile);                // convert path to Uri
    takePictureIntent.putExtra( MediaStore.EXTRA_OUTPUT,  picUri );
    startActivityForResult(takePictureIntent, CAMERA_CAPTURE);
} catch(ActivityNotFoundException e){
    //display an error message
    Toast.makeText(getActivity(), "Sorry your device doesn't support capturing images!",
            Toast.LENGTH_SHORT).show();
}

B- From Gallery :

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == getActivity().RESULT_OK) {
     ......
        else if(requestCode == PICK_IMAGE_REQUEST){
            picUri = data.getData();
             .....
        }
    }
}

for more information go to my post Capture And Crop Images.

How to show picUri in text :

String picUriText = picUri.toString();
content://media/external/images/media/109

4- Set Images from picUri

Bitmap imgBitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), picUri);
imageView.setImageBitmap(bitmap);

5- Getting Image Path

String path = picUri.getPath();
/external/images/media/109

6- Getting Image Real Path

private String getRealPathFromURI(Uri contentUri) {
    String[] proj = { MediaStore.Images.Media.DATA };
    CursorLoader loader = new CursorLoader(getContext(), contentUri, proj, null, null, null);
    Cursor cursor = loader.loadInBackground();
    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    cursor.moveToFirst();
    String result = cursor.getString(column_index);
    cursor.close();
    return result;
}
String realPath = getRealPathFromURI(picUri);
/storage/sdcard/DCIM/SharedFolder/3.jpg

7- Getting Image Base64 String

// Convert Image to String
public String getStringImage(Bitmap bmp){
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bmp.compress(Bitmap.CompressFormat.PNG, 0, baos);
    byte[] imageBytes = baos.toByteArray();
    String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
    return encodedImage;
}
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), picUri);
image_view.setImageBitmap(bitmap);                   // set image from camera or gallery
String imgData = getStringImage(bitmap);             // getting image data in base64 string
TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb24sIGJ1dCBieSB0aGlz .....

8- Set Image From Base64 String

byte[] decodedString = Base64.decode(imgData, Base64.DEFAULT);
Bitmap bitmap = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
image_view.setImageBitmap(bitmap);

9- Save Current Image To Another Folder

String sendDir = Environment.getExternalStorageDirectory().getAbsolutePath()+"/CircleEduventures/Images/";
private void saveFile(Uri sourceUri, File destination) {
    try {
        File source = new File(getRealPathFromURI(sourceUri));
        FileChannel src = new FileInputStream(source).getChannel();
        FileChannel dst = new FileOutputStream(destination).getChannel();
        dst.transferFrom(src, 0, src.size());
        src.close();
        dst.close();
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}
File newfile = new File(sendDir+"picture.jpg");
saveFile(picUri, newfile);

10- Getting File Name

String real_path = getRealPathFromURI(picUri);
String filename = real_path.substring(real_path.lastIndexOf("/")+1);
Real Path :
/storage/sdcard/DCIM/SharedFolder/3.jpg
File Name :
3.jpg

11- Create Random File Name

public static String random(int length){
    String alphabet = new String("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz");
    int n = alphabet.length();
    String result = new String();
    Random r = new Random();
    for (int i=0; i<length; i++)
        result = result + alphabet.charAt(r.nextInt(n));
    return result;
}

File newfile = new File(sendDir+random(6)+".jpg");
where 6 is length of file name

12- Getting Uri of New File

File newfile = new File(sendDir+random(17)+".jpg");
Uri newUri = Uri.fromFile(newfile);

13- Set Image From Uri

String real_path = getRealPathFromURI(picUri);
File newfile = new File(sendDir+random(12)+".jpg");
image_view.setImageURI(Uri.fromFile(new File(real_path)));

image_view.setImageURI(Uri.fromFile(newFile));

image_view.setImageURI(Uri.parse(picUri));

About the author

Akshay Raj

View all posts