I have an app, which has a button to select a photo from your gallery and it works fine and after selecting the image my app show came back to the activity and shows the image in an image View.
Every is working fine but sometimes ,when i select some particular images the preview is not showing. I have also tried to compress the image still its not working
My code is below..
In onCreate()
galeryBtn=(Button)findViewById(R.id.buttonGallery);
galeryBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
});
In onActivityResult(int requestCode, int resultCode, Intent 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
// Show the Selected Image on ImageView
ImageView imageView = (ImageView) findViewById(R.id.imgView);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
Try like this
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
switch (requestCode) {
case RESULT_LOAD_IMAGE:
if (resultCode == Activity.RESULT_OK) {
Uri selectedImage = intent.getData();
try {
Bitmap bitmapImage =decodeBitmap(selectedImage );
} catch (FileNotFoundException e) {
e.printStackTrace();
}
// Show the Selected Image on ImageView
ImageView imageView = (ImageView) findViewById(R.id.imgView);
imageView.setImageBitmap(bitmapImage);
}
And
public Bitmap decodeBitmap(Uri selectedImage) throws FileNotFoundException {
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(getContentResolver().openInputStream(selectedImage), null, o);
final int REQUIRED_SIZE = 100;
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp / 2 < REQUIRED_SIZE || height_tmp / 2 < REQUIRED_SIZE) {
break;
}
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
return BitmapFactory.decodeStream(getContentResolver().openInputStream(selectedImage), null, o2);
}
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.
The way you're trying to load a bitmap in onActivityResult() is not absolutely right. Sometimes you will not be able to open an image and your application can crash. You'd better use code like this:
Uri imageUri = data.getData();
InputStream imageStream = null;
try {
imageStream = getContentResolver().openInputStream(imageUri);
ImageView imageView = (ImageView) findViewById(R.id.imgView);
imageView.setImageBitmap(BitmapFactory.decodeStream(imageStream));
} catch (FileNotFoundException e) {
// Handle the error
} finally {
if (imageStream != null) {
try {
imageStream.close();
} catch (IOException e) {
// Ignore the exception
}
}
}
Add this after imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
imageView.setImageURI(selectedImage);
It work for me.
Related
I'm trying to create simple Contact app. Naturally there is Contact class with member variable mCurrentPhotoPath. An activity which is responsible for creating Contact, has an option to pick image from Gallery in the following way:
final Intent pickImage = new Intent(Intent.ACTION_GET_CONTENT);
pickImage.setType("image/*")
/*some code...*/
galleryButton.setOnClickListener((View v) -> {
startActivityForResult(pickImage, REQUEST_GALLERY_PHOTO);
});
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_GALLERY_PHOTO && resultCode == RESULT_OK){
photoTaken = true;
Uri selectedImage = data.getData();
Log.i("path", selectedImage.getPath()) //prints out: /document/image:292562
mPhotoView.setImageURI(selectedImage);
I am able to display selected image in ImageView (mPhotoView).
However, when I try to set Intent in different way, I get full path, but I cannot recreate file from that path and I get FileNotFoundException.
final Intent pickImage = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_GALLERY_PHOTO && resultCode == RESULT_OK){
photoTaken = true;
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
if (selectedImage != null) {
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
Log.i.("TAG", picturePath); //I get, /storage/emulated/0/Pictures/Viber/IMG-bbd54c96cc971a1700f92205937014c8-V.jpg
mPhotoFile = new File(picturePath);
cursor.close();
updatePhotoView(); //This method recreates image based on exact file path and witdh & height of ImageView where the picture is going to be placed;
}
}
}
Here is updatePhotoView()
private void updatePhotoView(int imageWidth, int imageHeight) {
if (mPhotoFile == null || !mPhotoFile.exists()) {
mPhotoView.setImageDrawable(null);
} else {
Bitmap bitmap = PictureUtils.getScaledBitmap(mPhotoFile.getPath(),imageWidth, imageHeight); // imageWidth & imageHeight are member variables of actiivty...
mPhotoView.setImageBitmap(bitmap);
}
}
I'm pretty sure this function works, because when I implemented option to take picture from camera (I created file with getExternalFilesDir(), and in any other activity when I passed string value of mCurrentPhotoPath, getScaledBitmap() managed to recreate image).
Here is getScaledBitmap():
public static Bitmap getScaledBitmap(String path, int destWidth, int destHeight) {
// Read in the dimensions of the image on disk
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, options);
float srcWidth = options.outWidth;
float srcHeight = options.outHeight;
// Figure out how much to scale down by
int inSampleSize = 1;
if (srcHeight > destHeight || srcWidth > destWidth) {
if (srcWidth > srcHeight) {
inSampleSize = Math.round(srcHeight / destHeight);
} else {
inSampleSize = Math.round(srcWidth / destWidth);
}
}
options = new BitmapFactory.Options();
options.inSampleSize = inSampleSize;
// Read in and create final bitmap
return BitmapFactory.decodeFile(path, options);
}
Just if anyone stumbles on similar problem. I solved my problem of getting images by using Glide library. Look it up, bunch of tutorials. I guess that this load function is doing heavy lifting in the background. Great thing! Here is how code looks like:
Glide.with(context)
.load(imageFilePath)
.apply(new RequestOptions().centerCrop())
.override(imageView.getWidth(), imageView.getHeight())
.into(imageView);
My app is working properly on all api till Kitkat but it's not working in lollipop. The moment i clicks for capturing a photo using camera in my app, it crashes.
cam.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent cameraIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
});
This is my onActivityResult()
case CAMERA_REQUEST: {
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();
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(picturePath, options);
int imageHeight = options.outHeight;
int imageWidth = options.outWidth;
String imageType = options.outMimeType;
options.inSampleSize = calculateInSampleSize(options,200,100);//512 and 256 whatever you want as scale
options.inJustDecodeBounds = false;
Bitmap yourSelectedImage = BitmapFactory.decodeFile(picturePath,options);
File pngDir = new File(Environment.getExternalStorageDirectory(),"PicUploadTemp");
if (!pngDir.exists()) {
pngDir.mkdirs();
}
File pngfile = new File(pngDir,"texture1.jpg");
FileOutputStream fOut;
try {
fOut = new FileOutputStream(pngfile);
yourSelectedImage.compress(Bitmap.CompressFormat.JPEG, 50,fOut);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Drawable d = Drawable.createFromPath(pngfile.getPath().toString());
rlLayout.setBackground(d);
yourSelectedImage.recycle();
// resizedBitmap.recycle();
xfile = pngfile;
}
break;
I want to compress the image and this above code is working amazingly for gingerbread, ICS , kitkat but not for Android L
I am getting null pointer Exception
Please suggest me some solution
Thanks in advance
Cannot really say anything about this without the logcat output, It may be becoming null in as a result of you using on of the deprecated method in the BitmapFacotry class.
Define these globally in your activity,
Intent cameraIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
private static final int CAMERA_REQUEST = 1888;
in button click call your camera intent like this
startActivityForResult(cameraIntent, CAMERA_REQUEST);
make sure to use
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
use this to retrieve photo
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_REQUEST && resultCode == getActivity().RESULT_OK) {
//get photo
Bitmap photo = (Bitmap) data.getExtras().get("data");
}
I'm having a simple problem that may seem easy, however, when I pick a image from the gallery and try to set it up the in imageview in onActivityResult, the error would show up.
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=Intent { dat=content://media/external/images/media/35 }} to activity {com.mypackagename/com.mypackagename.SQLiteActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
This error must be due to the null object. That would mean that no data was retreived? I percieve that the settings that I made had no problem, however, I may have missed something. I've set the sample code below.
This is the code that calls the gallery
public void settingImage(View v){
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
This code is for getting the results
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (data != null) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getApplicationContext().getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
// Log.d("Path", picturePath);
//sampleimage.setImageBitmap(BitmapFactory.decodeFile(picturePath));
// imgPath = picturePath;
icontext.setText(picturePath);
cursor.close();
} else {
}
}
Here's some settings
private static int RESULT_LOAD_IMAGE = 1;
basic sdk setup
minSdkVersion 14
targetSdkVersion 22
I have try this to get Bitmap,
code that calls the gallery picker,
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, SELECT_PHOTO);
getting the results of bitmap,
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch (requestCode) {
case SELECT_PHOTO:
if (resultCode == RESULT_OK) {
Uri selectedImage = imageReturnedIntent.getData();
//yourSelectedImage = BitmapFactory.decodeStream(imageStream);
try {
yourSelectedImage = decodeUri(selectedImage);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
// imgViewProfilePic.setImageBitmap(yourSelectedImage);
}
}
}
to decode uri,
private Bitmap decodeUri(Uri selectedImage) throws FileNotFoundException {
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(getContentResolver().openInputStream(selectedImage), null, o);
// The new size we want to scale to
final int REQUIRED_SIZE = 140;
// Find the correct scale value. It should be the power of 2.
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp / 2 < REQUIRED_SIZE
|| height_tmp / 2 < REQUIRED_SIZE) {
break;
}
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
return BitmapFactory.decodeStream(getContentResolver().openInputStream(selectedImage), null, o2);
}
I use below code to import an image from my Gallery to on my imageView. It is successful, but i want to resize the bitmap since app force close itself with heavy image imports.
String mPicPath1;
Button save;
ImageView logoview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_card);
mPicPath1 = null;
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", mPicPath1);
}
startActivity(intent);
}}
});
logoview=(ImageView)findViewById(R.id.logoview);
logoview.setScaleType(ScaleType.FIT_XY);
logoview.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View arg0) {
openGallerylogo();
}
});
private void openGallerylogo() {
// TODO Auto-generated method stub
Intent photoPickerIntent = new Intent(Intent.ACTION_GET_CONTENT);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, 1);
}
#Override
protected void onActivityResult(int requestCode, int resultcode, Intent data){
super.onActivityResult(requestCode, resultcode, data);
if (requestCode == 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));
}}
}
}
When i implement:
mPicPath1.setScaleType(ScaleType.FIT_XY);
Then i need to change mPicPath1 is from String to Bitmap. If i change then i have "The method decodeFile(String) in the type BitmapFactory is not applicable for the arguments " error in this line:
logoview.setImageBitmap(BitmapFactory.decodeFile(mPicPath1));
Can you please correct my code above to import big size images and can pass it to SecondActivity. Thank you.
You should use this :
public void decodeFile(String filePath) {
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, o);
// The new size we want to scale to
final int REQUIRED_SIZE = 2048;
// Find the correct scale value. It should be the power of 2.
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 3;
while (true) {
if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE)
break;
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
bmp = BitmapFactory.decodeFile(filePath, o2);
}
And call this function as:
decodeFile(mPicPath1 );
UPDATE:
You can use like in your code:
Make global Bitmap variable
Bitmap bmp ;
decodeFile(mPicPath1);
logoview.setImageBitmap(bmp);
Just go thorough with this to manage large bitmaps:
http://developer.android.com/training/displaying-bitmaps/load-bitmap.html
in my app i am trying to send images to a server that are stored in sd card. When i click a button it opens the sd card and shows the image in a grid view. From that the i want to upload the image which i am touching on it. I know to upload an image to a server, but i dont know to select an image from the sd card please help me.....
Following is my code....
public void library()
{
Intent myIntent = new Intent();
myIntent.setType("image/*");
myIntent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(myIntent,"Select Picture"), 101);
}
public void onActivityResult(int requestCode, int resultCode, Intent myIntent)
{
Intent data = null;
if (requestCode == 101 && data != null)
{
Uri selctedImageUri =data.getData();
}
else
{
Toast toast = Toast.makeText(this, "No Image is selected.", Toast.LENGTH_LONG);
toast.show();
}
}
how to proceed please help me.....
This is the Intent for getting Gallery images :
Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);
intent.setType("image/*");
intent.putExtra("return-data", true);
startActivityForResult(intent, 1);
Then this code is to set the image selected from the Gallery in the Image View :
Use On ActivityResult fro this :
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case 1:
if(requestCode == 1 && data != null && data.getData() != null){
Uri _uri = data.getData();
if (_uri != null) {
//User had pick an image.
Cursor cursor = getContentResolver().query(_uri, new String[] { android.provider.MediaStore.Images.ImageColumns.DATA }, null, null, null);
cursor.moveToFirst();
//Link to the image
final String imageFilePath = cursor.getString(0);
Log.v("imageFilePath", imageFilePath);
File photos= new File(imageFilePath);
Bitmap b = decodeFile(photos);
b = Bitmap.createScaledBitmap(b,150, 150, true);
ImageView imageView = (ImageView) findViewById(R.id.select_image);
imageView.setImageBitmap(b);
cursor.close();
}
}
super.onActivityResult(requestCode, resultCode, data);
}
}
This Method for Reducing the Size of Image ;
private Bitmap decodeFile(File f){
try {
//decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f),null,o);
//Find the correct scale value. It should be the power of 2.
final int REQUIRED_SIZE=70;
int width_tmp=o.outWidth, height_tmp=o.outHeight;
int scale=1;
while(true){
if(width_tmp/2<REQUIRED_SIZE || height_tmp/2<REQUIRED_SIZE)
break;
width_tmp/=2;
height_tmp/=2;
scale++;
}
//decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize=scale;
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
} catch (FileNotFoundException e) {}
return null;
}
In these method if you Pass a File that contains image it will Resize the image and returns BITMAP..