Android provide many views for different use in the android app. ImageView is one of the views provided by Android to display image.
We can add image on an ImageView from different sources.e.g.,
– adding an image from the drawable folder, you can find this folder in android project directory in android studio or eclipse.
– adding an image from phone storage.
– take a picture using the camera and set it on an ImageView.
So, let us create a simple project to display an image on ImageView:
1. Create a new project->Project Name(MyApplication)
2. Add an activity “MainActivity.java” and a XML file “activity_main.xml”.
1 2 3 4 5 6 7 8 |
public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //write code here } } |
1 2 3 4 5 6 7 8 9 10 11 12 |
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout 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="#88DFAB" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity"> </RelativeLayout> |
3. Create a method (setImage()) in MainActivity.java:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
private void selectImage() { final CharSequence[] items = {"Take Picture", "Select 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) { if (items[item].equals("Take Picture")) { Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); Toast.makeText(getApplicationContext(), "Take Picture", Toast.LENGTH_SHORT).show(); startActivityForResult(intent, TAKE_PHOTO); } else if (items[item].equals("Select from Library")) { Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.M edia.EXTERNAL_CONTENT_URI); intent.setType("image/*"); Toast.makeText(getApplicationContext(), "Select from Library", Toast.LENGTH_SHORT).show(); startActivityForResult(Intent.createChooser(intent, "Select File"), FROM_STORAGE); } else if (items[item].equals("Cancel")) { Toast.makeText(getApplicationContext(), "Cancel", Toast.LENGTH_SHORT).show(); dialog.dismiss(); } } }); builder.show(); } |
4. Here we are calling another activity using “startActivityForResult()” method. It returns the result on its completion. So, here is another method(onActivityResult()) associated with this. In this method, we will set the image in ImageView.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 |
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); File destination = null; if (resultCode == RESULT_OK) { if (requestCode == TAKE_PHOTO) { Bitmap thumbnail = (Bitmap) data.getExtras().get("data"); ByteArrayOutputStream bytes = new ByteArrayOutputStream(); thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes); 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(); } ((ImageView) findViewById(R.id.profile_image)).setImageBitmap(thumbnail); } else if (requestCode == FROM_STORAGE) { Log.d("FROM_STORAGE ", " FROM_STORAGE"); Uri selectedImageUri = data.getData(); String[] projection = {MediaStore.MediaColumns.DATA}; CursorLoader cursorLoader = new CursorLoader(MainActivity.this, selectedImageUri, p rojection, null, null, null); Cursor cursor = cursorLoader.loadInBackground(); int column_index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA); cursor.moveToFirst(); String selectedImagePath = cursor.getString(column_index); String fileNameSegments[] = selectedImagePath.split("/"); String fileName = fileNameSegments[fileNameSegments.length - 1]; Bitmap bm; BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeFile(selectedImagePath, options); final int REQUIRED_SIZE = 100; int scale = 1; while (options.outWidth / scale / 2 >= REQUIRED_SIZE && options.outHeight / scale / 2 >= REQUIRED_SIZE) scale *= 2; options.inSampleSize = scale; options.inJustDecodeBounds = false; bm = BitmapFactory.decodeFile(selectedImagePath, options); ((ImageView) findViewById(R.id.profile_image)).setImageBitmap(bm); } } } |
5. After doing this code we need to add permissions in AndroidManifest.xml:
1 2 |
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> |
Complete code is here:
MainActivty.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 |
package com.shop.myapplication; import android.app.Activity; import android.app.AlertDialog; import android.content.CursorLoader; import android.content.DialogInterface; import android.content.Intent; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.provider.MediaStore; import android.util.Log; import android.view.View; import android.widget.ImageView; import android.widget.Toast; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; public class MainActivity extends Activity { final int TAKE_PHOTO = 1; final int FROM_STORAGE = 2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); findViewById(R.id.browse).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { selectImage(); } }); } 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) { if (items[item].equals("Take Photo")) { Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); Toast.makeText(getApplicationContext(), "Take Photo", Toast.LENGTH_SHORT).show(); startActivityForResult(intent, TAKE_PHOTO); } else if (items[item].equals("Choose from Library")) { Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.M edia.EXTERNAL_CONTENT_URI); intent.setType("image/*"); Toast.makeText(getApplicationContext(), "Choose from Library", Toast.LENGTH_SHORT).show(); startActivityForResult(Intent.createChooser(intent, "Select File"), FROM_STORAGE); } else if (items[item].equals("Cancel")) { Toast.makeText(getApplicationContext(), "Cancel", Toast.LENGTH_SHORT).show(); dialog.dismiss(); } } }); builder.show(); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); File destination = null; if (resultCode == RESULT_OK) { if (requestCode == TAKE_PHOTO) { Bitmap thumbnail = (Bitmap) data.getExtras().get("data"); ByteArrayOutputStream bytes = new ByteArrayOutputStream(); thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes); 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(); } ((ImageView) findViewById(R.id.profile_image)).setImageBitmap(thumbnail); } else if (requestCode == FROM_STORAGE) { Log.d("FROM_STORAGE ", " FROM_STORAGE"); Uri selectedImageUri = data.getData(); String[] projection = {MediaStore.MediaColumns.DATA}; CursorLoader cursorLoader = new CursorLoader(MainActivity.this, selectedImageUri, p rojection, null, null, null); Cursor cursor = cursorLoader.loadInBackground(); int column_index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA); cursor.moveToFirst(); String selectedImagePath = cursor.getString(column_index); String fileNameSegments[] = selectedImagePath.split("/"); String fileName = fileNameSegments[fileNameSegments.length - 1]; Bitmap bm; BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeFile(selectedImagePath, options); final int REQUIRED_SIZE = 100; int scale = 1; while (options.outWidth / scale / 2 >= REQUIRED_SIZE && options.outHeight / scale / 2 >= REQUIRED_SIZE) scale *= 2; options.inSampleSize = scale; options.inJustDecodeBounds = false; bm = BitmapFactory.decodeFile(selectedImagePath, options); ((ImageView) findViewById(R.id.profile_image)).setImageBitmap(bm); } } } } |
activity_main.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout 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="#88DFAB" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity"> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_centerVertical="true" android:background="#FFFFFF" android:orientation="vertical" android:padding="4dp"> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_centerVertical="true" android:background="#FFFFFF" android:orientation="vertical" android:padding="4dp"> <ImageView android:id="@+id/profile_image" android:layout_width="200dp" android:layout_height="200dp" android:layout_centerHorizontal="true" android:layout_centerVertical="true" android:src="@drawable/maintenance" android:background="#000" /> </LinearLayout> <Button android:id="@+id/browse" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="#37474F" android:elevation="5dp" android:text="Browse" android:textColor="#FFFFFF" android:textSize="20sp" /> </LinearLayout> </RelativeLayout> |
AndroidManifest.xml:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.shop.myapplication" > <uses-sdk android:minSdkVersion="17" android:targetSdkVersion="21" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/AppTheme" > <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> |