Get Image from the Gallery and Show in Imageview

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.

Select image from gallery and show in imageview

ImagePicker : please credit the developer when using their library

In your if statement inside of onActivityResult change requestCode to requestCode & 0xffff.

What many people don't notice here is that the requestCode that is coming back is coming back as a hex number not as a digit number.

In your AndroidManifest.xml add these permissions:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />

Use this method to pick up images:

protected  void onImageViewClick(){
// ImageView imageView=(ImageView)findViewById(R.id.imageView2);
TextView tw=(TextView)findViewById(R.id.addimage);
tw.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
selectImage();
}
});

}

private void selectImage() {
Intent takeImageIntent = ImagePicker.getPickImageIntent(this);
if (takeImageIntent.resolveActivity(getActivity().getPackageManager()) != null) {
startActivityForResult(takeImageIntent, REQUEST_IMAGE_CAPTURE);
}
}

Then use this to receive them:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Bitmap bitmap = ImagePicker.getBitmapFromResult(this, resultCode, data);
if (null != bitmap && resultCode == RESULT_OK) {
//do what you want with the bitmap here

}
}

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.

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

}

}
}

pick image from gallery and display in imagae view

Finnay this Code is working and we can give fixed size of imageview that display in particular area
layout.xml

 <Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Image Upload"
android:id="@+id/buttonImage"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />

<ImageView

android:layout_width="100dp"
android:layout_height="100dp"
android:id="@+id/imageView"
android:layout_x="13dp"
android:layout_y="112dp" />
Main Activity

Button imageUpload;
ImageView imageView;
static final int PICTURE = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView= (ImageView) findViewById(R.id.imageView);
imageUpload= (Button) findViewById(R.id.buttonImage);
imageUpload.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent,PICTURE);

}
});
}

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

if (requestCode==PICTURE && resultCode==RESULT_OK && null !=data)
{

Uri uri = data.getData();
String[] prjection ={MediaStore.Images.Media.DATA};
Cursor cursor=getContentResolver().query(uri,prjection,null,null,null);
cursor.moveToFirst();

int columnIndex=cursor.getColumnIndex(prjection[0]);
String path=cursor.getString(columnIndex);
cursor.close();

Bitmap selectFile = BitmapFactory.decodeFile(path);

Drawable d = new BitmapDrawable(selectFile);
imageView.setBackground(d);

// imageView.setImageBitmap(BitmapFactory.decodeFile(path));
}

}

Finally this code is working

Picking a photo from gallery and show in a image view

I run into similar problems like getting cursor uri from resource, open stream, set bitmap etc. And it has bugs all the time.

So I searched libraries and found image-chooser-library library.

I bet you would like to try this project from image-chooser-library

It is very easy to use and solves all those nitty gritty problems for you, like images from picasa etc.

Hopefully it is useful for you.

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;
}
}
}

how to get image from gallery and show it in imageview?

It is very easy check this code. good luck

public class MainActivity extends Activity {

Button btn1;
ImageView img;
private static int LOAD_IMAGE_RESULTS = 1;
Bitmap mBitmap;

@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

btn1 = (Button) findViewById(R.id.button1);
edit = (EditText) findViewById(R.id.editText1);
img = (ImageView) findViewById(R.id.ImageView1);

img.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

// Start new activity with the LOAD_IMAGE_RESULTS to handle back the results when image is picked from the Image Gallery.
startActivityForResult(i, LOAD_IMAGE_RESULTS);

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

// Here we need to check if the activity that was triggers was the Image Gallery.
// If it is the requestCode will match the LOAD_IMAGE_RESULTS value.
// If the resultCode is RESULT_OK and there is some data we know that an image was picked.
if (requestCode == LOAD_IMAGE_RESULTS && resultCode == RESULT_OK && data != null) {
// Let's read picked image data - its URI
Uri pickedImage = data.getData();
// Let's read picked image path using content resolver
String[] filePath = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(pickedImage, filePath, null, null, null);
cursor.moveToFirst();
imagePath = cursor.getString(cursor.getColumnIndex(filePath[0]));

// Now we need to set the GUI ImageView data with data read from the picked file.
mBitmap = BitmapFactory.decodeFile(imagePath);
img.setImageBitmap(BitmapFactory.decodeFile(imagePath));

// At the end remember to close the cursor or you will end with the RuntimeException!
cursor.close();
}
}

}

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