Choose an image from gallery and show it using an ImageView - android

private static int RESULT_LOAD = 1;
String img_Decodable_Str;
ImageView imageView = (ImageView) findViewById(R.id.Gallery);
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
// Start the Intent
startActivityForResult(galleryIntent, RESULT_LOAD);
}
});}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
// When an Image is picked
if (requestCode == RESULT_LOAD && resultCode == RESULT_OK
&& null != data) {
// Get the Image from data
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
// Get the cursor
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
// Move to first row
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
img_Decodable_Str = cursor.getString(columnIndex);
cursor.close();
ImageView imageView = (ImageView) findViewById(R.id.Gallery);
// Set the Image in ImageView after decoding the String
imageView.setImageBitmap(BitmapFactory
.decodeFile(img_Decodable_Str));
} else {
Toast.makeText(this, "Hey pick your image first",
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(this, "Something went embrassing", Toast.LENGTH_LONG)
.show();
}
}}
I have an ImageView. If the user clicks on the ImageView he will be able to add an image of his choice to it. When i click on the ImageView I'm redirected to gallery but when i choose an image, that image isn't showing in the ImageView. where have i gone wrong?

In the short term, replace:
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
// Get the cursor
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
// Move to first row
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
img_Decodable_Str = cursor.getString(columnIndex);
cursor.close();
ImageView imageView = (ImageView) findViewById(R.id.Gallery);
// Set the Image in ImageView after decoding the String
imageView.setImageBitmap(BitmapFactory
.decodeFile(img_Decodable_Str));
with:
Uri selectedImage = data.getData();
imageView.setImageURI(selectedImage);
Later, use an image-loading library, such as Picasso or Glide, as setImageURI() loads the image on the main application thread, which will freeze your UI for as long as that work takes.

Related

The picture is not being shown when clicked on addImage button. What is missing in the code?

I am trying to add Image from Gallery to show up in my app. But it is not showing after I select the image from the gallery. It is not showing any error and runs successfully on my device.
private static int RESULT_LOAD_IMAGE=1;
public void addImage(View view){
Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 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.memeImage);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
}
try this with uri
imageView.setImageUri(selectedImage )

How do we check image size before inserting in imageview in android?

I have an app which contain a "imageview" and a "button" known as uploadImage. when i click uploadimage it is opening a a chooser option from where user can choose image and set it in imageview. Problem is that before setting image in image view i want to check whether image size is not more that 200 kb if found then show toast message otheriwse proceed further.
code:-
private void showFileChooser() {
// Create intent to Open Image applications like Gallery, Google Photos
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent,PICK_IMAGE_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
// When an Image is picked
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK
&& null != data) {
// Get the Image from data
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
// Get the cursor
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
// Move to first row
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
imgDecodableString = cursor.getString(columnIndex);
cursor.close();
// Set the Image in ImageView after decoding the String
m_UploadImage.setImageBitmap(BitmapFactory
.decodeFile(imgDecodableString));
} else {
Toast.makeText(this, "You haven't picked Image",
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG)
.show();
}
}
You can check the image size using the following Code:
Bitmap bitImage = BitmapFactory.decodeResource(getResources(),
R.drawable.ic_launcher);// For example I took ic_launcher
Bitmap bitmap = bitImage;
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] imageInByte = stream.toByteArray();
long sizeOfImage = imageInByte.length; //Image size
Your Code :
private void showFileChooser() {
// Create intent to Open Image applications like Gallery, Google Photos
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent,PICK_IMAGE_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
// When an Image is picked
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK
&& null != data) {
// Get the Image from data
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
// Get the cursor
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
// Move to first row
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
imgDecodableString = cursor.getString(columnIndex);
cursor.close();
// Set the Image in ImageView after decoding the String
Bitmap bitImage = BitmapFactory.decodeFile(imgDecodableString);
Bitmap bitmap = bitImage;
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] imageInByte = stream.toByteArray();
long sizeOfImage = imageInByte.length; //Image size
//Code to check image size greater than 20KB
if(sizeofImage/1024 > 200){
Toast.makeText(this, "Image size more than 200KB", Toast.LENGTH_LONG)
}else{
m_UploadImage.setImageBitmap(bitImage);
}
} else {
Toast.makeText(this, "You haven't picked Image",
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG)
.show();
}
}
Or you can try this way ,
First you get the Bitmap attached on the ImageView:
using this :
Bitmap bitmap = ((BitmapDrawable)image.getDrawable()).getBitmap();
In your code :
private void showFileChooser() {
// Create intent to Open Image applications like Gallery, Google Photos
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent,PICK_IMAGE_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
// When an Image is picked
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK
&& null != data) {
// Get the Image from data
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
// Get the cursor
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
// Move to first row
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
imgDecodableString = cursor.getString(columnIndex);
cursor.close();
// Set the Image in ImageView after decoding the String
m_UploadImage.setImageBitmap(BitmapFactory
.decodeFile(imgDecodableString));
//Get the Bitmap in your ImageView
Bitmap bitmap = ((BitmapDrawable)m_UploadImage.getDrawable()).getBitmap();
// Then check the Image size
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] imageInByte = stream.toByteArray();
long lengthbmp = imageInByte.length;
Toast.makeText(this, "Length of the Image :" + lengthbmp,
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(this, "You haven't picked Image",
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG)
.show();
}
}
Better you create a an another class and write this public method in that class because in future you can use this class.
public class UtilClassName{
public static int getFileSize(Uri imageUri,Activity activity){
int kb_size=0;
try {
InputStream is=activity.getContentResolver().openInputStream(imageUri);
int byte_size=is.available();
int kb_size=byte_size/1024;
}
catch (Exception e){
// here you can handle exception here
}
return kb_size;
}
}
In your code use this logic
if(UtilClassName.getFileSize(selectedImage,this)<=200){
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
// Move to first row
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
imgDecodableString = cursor.getString(columnIndex);
cursor.close();
// Set the Image in ImageView after decoding the String
m_UploadImage.setImageBitmap(BitmapFactory
.decodeFile(imgDecodableString));
}
else{
//show a warning to the user
}
Try this method and if you are facing any issue let me know. I had faced this problem before and i created this method for a file compressor class. I hope you will get solution.

how to select image in one class and display it on image view on other class

i am using a button to select an image from gallery and the image will be set to imageview which is on other screen:
//setimg button is on firstscreen.xml
setimg.setOnClickListener(new 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();
// String picturePath contains the path of selected Image
ImageView iv_wallset = (ImageView) findViewById(R.id.iv_wallset);
iv_wallset.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
}
}
// Imageview iv_wallset is on second.xml
can we use intent.putextra() to carry image from one screen to other???
Yes, you can put an extra String in the intent and from the second activity get the argument and decode the picture:
in activity 1:
mIntent.putExtra("image_path", picturePath);
in activity 2:
String path = getIntent().getStringExtra("image_path");
ImageView imageView = (ImageView) findViewById(R.id.iv_wallset);
imageView.setImageBitmap(BitmapFactory.decodeFile(path));
yes convert image into byte array and pass that byte array to other activity.

Image resolution or size issue gives 'Force Close' error

I have 2 imageView to import images from gallery and set on these imageViews. I basically do this by:
String mPicPath1, mPicPath2;
protected void onCreate(Bundle icicle) {
mPicPath1 = null;
mPicPath2 = null;
}
#Override
protected void onActivityResult(int requestCode, int resultcode, Intent data){
super.onActivityResult(requestCode, resultcode, data);
switch(requestCode){
case 1:
if (data != null && resultcode == RESULT_OK)
{
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]);
mPicPath1 = cursor.getString(columnIndex);
cursor.close();
logoview.setBackgroundResource(0);
logoview.setImageBitmap(BitmapFactory.decodeFile(mPicPath1));
}
break;
case 2:
if (data != null && resultcode == RESULT_OK)
{
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
cursor.moveToFirst();
mPicPath2 = cursor.getString(columnIndex);
cursor.close();
qrcodeview.setBackgroundResource(0);
qrcodeview.setImageBitmap(BitmapFactory.decodeFile(mPicPath2));
}
break;
}
and i use a button onClickListener to start intent and go to SecondActivity:
save=(Button)findViewById(R.id.save);
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(NewCard.this, Template.class);
if (!TextUtils.isEmpty(mPicPath1)) {
intent.putExtra("picture_path1", PicPath1);
}
if (!TextUtils.isEmpty(mPicPath2)) {
intent.putExtra("picture_path2", PicPath2);
}
startActivity(intent);
}
});
And my SecondActivity to set images on 2 different imageViews:
String pre_img_path1= getIntent().getStringExtra("picture_path1");
ImageView crdlogoframe = (ImageView) findViewById(R.id.crdlogoframe);
crdlogoframe.setImageBitmap(BitmapFactory.decodeFile(pre_img_path1));
String pre_img_path2= getIntent().getStringExtra("picture_path2");
ImageView crdqrframe = (ImageView) findViewById(R.id.crdqrframe);
crdqrframe.setImageBitmap(BitmapFactory.decodeFile(pre_img_path2));
So my problem is about the file size or resolution of the images. If i take 2 high resolution images from gallery (taken by standard camera: 1992kb, 3264x2448) and i click my save (save.onClickListener) button, i receive Force Close error. If i take small size images there is no problem(74kb, 800x600) i can proceed SecondActivity and see images are set. How i can solve this issue. Should i use a syntax to resize the images when i pick or set. The formats are both .Jpeg. Thank you very much.
i do not have the rep to comment yet so .... but as Simon said your images are to large 31MB need to try and keep things under about 16MB so you will have to re-size them before you can display them
Instead of
BitmapFactory.decodeFile(mPicPath2)
You need to use something like
BitmapFactory.decodeFile(mPicPath2, options)
Where options is an instance of BitmapFactory.Options with an inSampleSize set to something like 4 that will scale down the image as it is loaded.

Pick Gallery Image In Android Causing Issue

I am using a very simple code to pick image from gallery, it work on my phone.
but testing it on three to four phones(Galaxy S3,Tablet etc..) it does not work.
Environment It Works:
if the image size i took or was in gallery below 500kb then it works
Environment It Does'nt Work:
if the image size i took or was in gallery above 500kb then it works
ImageView myimg;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Toast.makeText(this, UUID.randomUUID().toString(),
// Toast.LENGTH_LONG).show();
myimg = (ImageView) findViewById(R.id.imageView1);
mybutton = (Button) findViewById(R.id.myButton);
mybutton.setOnClickListener(this);
}
public void onClick(View v) {
if (v == mybutton) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, 0);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent imageReturnedIntent) {
switch (requestCode) {
case 0:
if (resultCode == RESULT_OK) {
Uri selectedImage = imageReturnedIntent.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 filePath = cursor.getString(columnIndex); // file path of
// selected
// image
cursor.close();
// Convert file path into bitmap image using below line.
Bitmap yourSelectedImage = BitmapFactory.decodeFile(filePath);
// put bitmapimage in your imageview
myimg.setImageBitmap(yourSelectedImage);
}
}
}
Any one put some light on it how to handle this situation?
Any help would be appreciated.

Categories

Resources