This example demonstrates how to pick an image from an image gallery on Android using Kotlin. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml.
you will have to get the numeric "ID" of the image path say "fileString". This means if the path is "some/somthing/4" then 4 is the ID of that image. This original ID should be passed on to getThumbnail().
Simple pass Intent
first:
Intent i = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
And you will get picture path on your onActivityResult
:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
ImageView imageView = (ImageView) findViewById(R.id.imgView);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
}
for full source code here
@parag's code works great. But while loading some large images you may fail. You should use;
imageView.setImageBitmap(getScaledBitmap(picturePath, 800, 800));
instead of;
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
Here are my methods that you can use.
private Bitmap getScaledBitmap(String picturePath, int width, int height) {
BitmapFactory.Options sizeOptions = new BitmapFactory.Options();
sizeOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(picturePath, sizeOptions);
int inSampleSize = calculateInSampleSize(sizeOptions, width, height);
sizeOptions.inJustDecodeBounds = false;
sizeOptions.inSampleSize = inSampleSize;
return BitmapFactory.decodeFile(picturePath, sizeOptions);
}
private int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
// Calculate ratios of height and width to requested height and
// width
final int heightRatio = Math.round((float) height / (float) reqHeight);
final int widthRatio = Math.round((float) width / (float) reqWidth);
// Choose the smallest ratio as inSampleSize value, this will
// guarantee
// a final image with both dimensions larger than or equal to the
// requested height and width.
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
}
return inSampleSize;
}
This is the easiest way to get image from gallery and crop ass well
step 1: StartActivity for result
imageUser.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.INTERNAL_CONTENT_URI);
intent.setType("image/*");
intent.putExtra("crop", "true");
intent.putExtra("scale", true);
intent.putExtra("outputX", 256);
intent.putExtra("outputY", 256);
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
intent.putExtra("return-data", true);
startActivityForResult(intent, 1);
}
});
step 2:Handle the result
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode != RESULT_OK) {
return;
}
if (requestCode == 1) {
final Bundle extras = data.getExtras();
if (extras != null) {
//Get image
Bitmap ProfilePic = extras.getParcelable("data");
imageUser.setImageBitmap(ProfilePic);
TextView t=(TextView)findViewById(R.id.textoverimage);
t.setText("image Selected");
}
}
}
Run the app in debug mode and set a breakpoint on if (requestCode == SELECT_PICTURE)
and inspect each variable as you step through to ensure it is being set as expected. If you are getting a NPE on img.setImageURI(selectedImageUri);
then either img
or selectedImageUri
are not set.
import android.content.Intent;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
public class MainActivity extends AppCompatActivity {
ImageView img;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
img = (ImageView)findViewById(R.id.imageView);
}
public void btn_gallery(View view) {
Intent intent =new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI);
startActivityForResult(intent,100);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode==100 && resultCode==RESULT_OK)
{
Uri uri = data.getData();
img.setImageURI(uri);
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With