Android Get Image from Gallery into Imageview

get selected image from gallery into imageview

here is the code to load an image from gallery:

public class ImageGalleryDemoActivity extends Activity {


private static int RESULT_LOAD_IMAGE = 1;


@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

Button buttonLoadImage = (Button) findViewById(R.id.buttonLoadPicture);
buttonLoadImage.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View arg0) {

Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

startActivityForResult(i, RESULT_LOAD_IMAGE);
}
});
}


@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));

}


}
}

import an image from gallery and set it to an imageview

I'll share what I think should help you far enough. You can refactor to meet your resources.
This will help you get image from both gallery and camera. To crop images, I'd recommend a library like uCrop or edmodo cropper.

public class MainActivity extends Activity {

private int REQUEST_CAMERA = 0, SELECT_FILE = 1;
private Button btnSelect;
private ImageView ivImage;
private String userChoosenTask;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

btnSelect = (Button) findViewById(R.id.btnSelectPhoto);
btnSelect.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
selectImage();
}
});
ivImage = (ImageView) findViewById(R.id.ivImage);
}

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case Utils.MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if(userChoosenTask.equals("Take Photo"))
cameraIntent();
else if(userChoosenTask.equals("Choose from Library"))
galleryIntent();
} else {
//code for deny
}
break;
}
}

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) {
boolean result=Utils.checkPermission(MainActivity.this);

if (items[item].equals("Take Photo")) {
userChoosenTask ="Take Photo";
if(result)
cameraIntent();

} else if (items[item].equals("Choose from Library")) {
userChoosenTask ="Choose from Library";
if(result)
galleryIntent();

} else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}

private void galleryIntent()
{
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);//
startActivityForResult(Intent.createChooser(intent, "Select File"),SELECT_FILE);
}

private void cameraIntent()
{
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAMERA);
}

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

if (resultCode == Activity.RESULT_OK) {
if (requestCode == SELECT_FILE)
onSelectFromGalleryResult(data);
else if (requestCode == REQUEST_CAMERA)
onCaptureImageResult(data);
}
}

private void onCaptureImageResult(Intent data) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);

File 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();
}

ivImage.setImageBitmap(thumbnail);
}

@SuppressWarnings("deprecation")
private void onSelectFromGalleryResult(Intent data) {

Bitmap bm=null;
if (data != null) {
try {
bm = MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(), data.getData());
} catch (IOException e) {
e.printStackTrace();
}
}

ivImage.setImageBitmap(bm);
}

}

Create the Utils class

public class Utils {
public static final int MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE = 123;

@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public static boolean checkPermission(final Context context)
{
int currentAPIVersion = Build.VERSION.SDK_INT;
if(currentAPIVersion>=android.os.Build.VERSION_CODES.M)
{
if (ContextCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale((Activity) context, Manifest.permission.READ_EXTERNAL_STORAGE)) {
AlertDialog.Builder alertBuilder = new AlertDialog.Builder(context);
alertBuilder.setCancelable(true);
alertBuilder.setTitle("Permission necessary");
alertBuilder.setMessage("External storage permission is necessary");
alertBuilder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public void onClick(DialogInterface dialog, int which) {
ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
}
});
AlertDialog alert = alertBuilder.create();
alert.show();

} else {
ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
}
return false;
} else {
return true;
}
} else {
return true;
}
}
}

Get Image from the Gallery and Show in ImageView

you can try this.

paste this code in your button click event.

Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, RESULT_LOAD_IMG);

and below code is your on activity result

@Override
protected void onActivityResult(int reqCode, int resultCode, Intent data) {
super.onActivityResult(reqCode, resultCode, data);


if (resultCode == RESULT_OK) {
try {
final Uri imageUri = data.getData();
final InputStream imageStream = getContentResolver().openInputStream(imageUri);
final Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);
image_view.setImageBitmap(selectedImage);
} catch (FileNotFoundException e) {
e.printStackTrace();
Toast.makeText(PostImage.this, "Something went wrong", Toast.LENGTH_LONG).show();
}

}else {
Toast.makeText(PostImage.this, "You haven't picked Image",Toast.LENGTH_LONG).show();
}
}

I hope it is helpful for you.

Android get image from gallery into ImageView

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.

How to display an image from the Gallery in an ImageView?

Few Intent actions use EXTRA_OUTPUT. Mostly, that is an ACTION_IMAGE_CAPTURE thing.

More typically, an Intent for getting a piece of content (ACTION_PICK, ACTION_GET_CONTENT, ACTION_OPEN_DOCUMENT, ACTION_CREATE_DOCUMENT, ACTION_OPEN_DOCUMENT_TREE, etc.) return a Uri from the content supplier in the Intentdelivered toonActivityResult(). Given your implementation, that would be data.getData()to get thatUri`.

You can then use a ContentResolver and openInputStream() to get an InputStream on the content identified by the Uri. In your case, for example, you could use that InputStream to copy the bytes to a FileOutputStream to make your own local copy of the content.

Note that you only have short-term access to the content identified by the Uri.

android pick images from gallery

Absolutely. Try this:

Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE);

Don't forget also to create the constant PICK_IMAGE, so you can recognize when the user comes back from the image gallery Activity:

public static final int PICK_IMAGE = 1;

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == PICK_IMAGE) {
//TODO: action
}
}

That's how I call the image gallery. Put it in and see if it works for you.

EDIT:

This brings up the Documents app. To allow the user to also use any gallery apps they might have installed:

    Intent getIntent = new Intent(Intent.ACTION_GET_CONTENT);
getIntent.setType("image/*");

Intent pickIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
pickIntent.setType("image/*");

Intent chooserIntent = Intent.createChooser(getIntent, "Select Image");
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[] {pickIntent});

startActivityForResult(chooserIntent, PICK_IMAGE);

How do you upload an image from Gallery into an imageview?

While loading local image you have path should be like this "file:///image_path.jpg".

Replace

Picasso.with(this).load(user_image_path).fit().centerCrop().into(myImageView);

with

Picasso.with(this).load("file:///"+user_image_path).fit().centerCrop().into(myImageView);

Image picked from gallery is not getting set in image view

I found the Solution for the question, now I am able to set the image to imageview by both camera and gallery, what I needed to do was add real-time permission for api23+,Change the code of selectImage() in above code.

private void selectImage() {

final CharSequence[] options = { "Take Photo", "Choose from Gallery","Cancel" };

AlertDialog.Builder builder = new AlertDialog.Builder(student_form.this);
builder.setTitle("Add Photo!");
builder.setItems(options, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int item) {
if (options[item].equals("Take Photo"))
{
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

startActivityForResult(intent, 1);
}
else if (options[item].equals("Choose from Gallery"))
{

Intent intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 2);

}
else if (options[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}

@SuppressLint("LongLogTag")
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
Bitmap bitmap = (Bitmap) data.getExtras().get("data");
imageview.setImageBitmap(bitmap);

}

} else if (requestCode == 2) {



String[] galleryPermissions = {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};

if (EasyPermissions.hasPermissions(this, galleryPermissions)) {
Uri selectedImage = data.getData();
String[] filePath = { MediaStore.Images.Media.DATA };
Cursor c = getContentResolver().query(selectedImage,filePath, null, null, null);
c.moveToFirst();

int columnIndex = c.getColumnIndex(filePath[0]);
String picturePath = c.getString(columnIndex);
c.close();

Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
imageview.setImageBitmap(thumbnail);
} else {
EasyPermissions.requestPermissions(this, "Access for storage",
101, galleryPermissions);
}


}
}

add the following code at the end just above the last curly bracket this is to check real time permission for camera

 public void EnableRuntimePermission(){
final int RequestPermissionCode = 1 ;

if (ActivityCompat.shouldShowRequestPermissionRationale(student_form.this,
Manifest.permission.CAMERA))
{

Toast.makeText(student_form.this,"CAMERA permission allows us to Access CAMERA app", Toast.LENGTH_LONG).show();

} else {

ActivityCompat.requestPermissions(student_form.this,new String[]{
Manifest.permission.CAMERA}, RequestPermissionCode);

}
}

@Override
public void onRequestPermissionsResult(int RC, String per[], int[] PResult) {

final int RequestPermissionCode = 1 ;
switch (RC) {

case RequestPermissionCode:

if (PResult.length > 0 && PResult[0] == PackageManager.PERMISSION_GRANTED) {

Toast.makeText(student_form.this,"Permission Granted, Now your application can access CAMERA.", Toast.LENGTH_LONG).show();

} else {

Toast.makeText(student_form.this,"Permission Canceled, Now your application cannot access CAMERA.", Toast.LENGTH_LONG).show();

}
break;
}
}

and also don't forget to call method EnableRuntimePermission(); at the start when initialising variables.



Related Topics



Leave a reply



Submit