I am trying to set the picture that the user chooses from their gallery, by using Uri, as their background for an app, but I cant quite figure it out. One thing that I tried doing was straight up setting the background to the uri, but it fails do to compatibility mismatch. How can I do this, either by programmatically setting the drawable or any other way at at all?
Here is what I have tried
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if (requestCode == 1) {
if (intent != null && resultCode == RESULT_OK) {
Uri selectedImage = intent.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);
cursor.close();
if (bmp != null && !bmp.isRecycled()) {
bmp = null;
}
bmp = BitmapFactory.decodeFile(filePath);
imageView.setBackground(selectedImage);//error here
//imageView.setBackgroundResource(0);//originally this, but this crashes also
imageView.setImageBitmap(bmp);
}
}
}
Check out this link Retrieve drawable resource from Uri
try {
InputStream inputStream = getContentResolver().openInputStream(yourUri);
yourDrawable = Drawable.createFromStream(inputStream, yourUri.toString() );
imageView.setImageDrawable(yourDrawable);
} catch (FileNotFoundException e) {
yourDrawable = getResources().getDrawable(R.drawable.default_image);
}
Related
I write this code and my code choose one picture from gallery and get data from it but I dont konw how to get image address from Inputstrem or data and store it?
public void loadPic()
{
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, 1);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==1)
{
try {
Uri selectedImage=data.getData();
InputStream inputStream = getContentResolver().openInputStream(selectedImage);
listItems.add(inputStream.toString());
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
Read filename name like below, use it accordingly.
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);
File f = new File(picturePath);
String imageName = f.getName();
Sometimes, you can't get a file from the picture you choose.
It's because the choosen one came from Google+, Drive, Dropbox or any other provider.
The best solution is to ask the system to pick a content via Intent.ACTION_GET_CONTENT and get the result with a content provider.
public void pickImage() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, PICK_PHOTO_FOR_AVATAR);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_PHOTO_FOR_AVATAR && resultCode == Activity.RESULT_OK) {
if (data == null) {
//Display an error
return;
}
InputStream inputStream = context.getContentResolver().openInputStream(data.getData());
//Now you can do whatever you want with your inpustream, save it as file, upload to a server, decode a bitmap...
}
}
I'm not sure if this is exactly what you want, but you can get the image like this:
Uri selectedImage = data.getData();
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), selectedImage);
Once you have the Bitmap, you can see here on how to store it.
EDIT: Try this
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));
Taken from here.
I'm trying to select a background image from gallery and set it as Activity background. But the problem is here when I set RelativeLayout instead of ImageView, it gives me error on setImageBitmap, what;s the reason here? Here's my code: I referred to this tutorial : http://viralpatel.net/blogs/pick-image-from-galary-android-app/ Thanks in advance!
#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.background);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
}
That is because RelativeLayout doesn't have a method called setImageBitmap.
Referring to this link, you can use this to set it to your relative layout:
File f = new File(getRealPathFromURI(path));
Drawable d = Drawable.createFromPath(f.getAbsolutePath());
mRelativeLayout.setBackground(d);
private String getRealPathFromURI(Uri contentURI) {
Cursor cursor = getContentResolver().query(contentURI, null, null, null, null);
if (cursor == null) { // Source is Dropbox or other similar local file path
return contentURI.getPath();
} else {
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
return cursor.getString(idx);
}
}
You can't do setImageBitmap on a RelativeLayout. I think what you want to do is setBackground which takes in a Drawable as parameter.
I am little stuck on a query. searched a lot but didn't get desired result..So please help me to Solve this problem..
I want to Select Image from Gallery and I got success in it.. but now I want to get thumbnail path too..
I know I can Create Thumbnail From Image path...but i want string path of thumbnail so i can use it in array....
So When I select any image from gallery I want these two paths..
Image Path
Thumbnail Path or ID of Selected Image
My Code..
to Open Gallery..
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, RESULT_LOAD_IMAGE);
OnActivityResult()
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
path = null;
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]);
path = cursor.getString(columnIndex);
long imageId = cursor.getLong(columnIndex); //getting 0 here... i thought it could give me image id.. :p
Log.v("AddEventDataActivity", "Selected Image Path : " + path); // getting image path successfully...
Log.v("AddEventDataActivity", "Selected Image ID : " + imageId); // ???
cursor.close();
// tried this but not succeed.. :(
Cursor thumbcursor = MediaStore.Images.Thumbnails
.queryMiniThumbnail(getContentResolver(), imageId,
MediaStore.Images.Thumbnails.MINI_KIND, null);
if (thumbcursor != null && thumbcursor.getCount() > 0) {
thumbcursor.moveToFirst();// **EDIT**
thumbpath = thumbcursor.getString(thumbcursor
.getColumnIndex(MediaStore.Images.Thumbnails.DATA));
}
thumbcursor.close();
Log.v("THUMB", "THUMBNAIL PATH : " + thumbpath); // no value to thumbpath...
}
}
I could not find how to solve that...
Any help would be helpful...
for getting Thumbnail
Bitmap bitmap = MediaStore.Images.Thumbnails.getThumbnail(
getContentResolver(), selectedImageUri,
MediaStore.Images.Thumbnails.MINI_KIND,
(BitmapFactory.Options) null );
where selectedImageUri = data.getData();
I know this is old, but this worked for me:
#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();
try {
Long thumbId = Long.parseLong(selectedImage.getLastPathSegment());
Bitmap bitmap = MediaStore.Images.Thumbnails.getThumbnail(
getContentResolver(),
thumbId,
MediaStore.Images.Thumbnails.MINI_KIND,
null
);
} catch (NumberFormatException e) {
//Handle exception
}
}
}
i have to change the color of just one pixel of an selected image from gallery
i used a button to change this pixel but always the application has forced to stop when i clicked the button
plz help me to solve this problem :(
this is my button code
public void btnClick2 (View v){
bmp.setPixel(30,30,0xFF000000 );
}
and this is onactivityresult code
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == SELECTED_PICTURE && 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();
bmp = BitmapFactory.decodeFile(picturePath);
iv1.setImageBitmap(bmp);
}
}
it does force close because BitmapFactory.decodeFile returns an immutable Bitmap, while setPixel works only on mutable bitmaps. You can use Bitmap.copy to get a mutable version of the original bitmap.
Edit:
Bitmap tmpBmp = BitmapFactory.decodeFile(picturePath);
bmp = tmpBmp.copy(Bitmap.Config.ARGB_8888 ,true);
I'm trying to get the path of the selected file from gallery, but it is returning null and I don't know why. Every code I see uses the same approach, but it doesn't work for me. Here is my code:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// LOAD_FILE_REQUEST is a global variable:
// private static final int LOAD_FILE_REQUEST = 1;
if (requestCode == LOAD_FILE_REQUEST && resultCode == RESULT_OK && data != null) {
if(data.getData() == null) {
System.out.println("NULL");
} else {
System.out.println("NOT NULL"); // <--- Printed
}
currImageURI = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(currImageURI, filePathColumn, null, null, null);
if(cursor.moveToFirst()){
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String yourRealPath = cursor.getString(columnIndex);
System.out.println("REAL PATH "+yourRealPath);
} else {
System.out.println("NO ROWS!!!"); // <-- Not printed
}
cursor.close();
}
}
Did you add the following line in your manifest ? =]
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Could you explain a little more what your problem is? Where are you getting a null?
In which Android version are you running this code? From Android 4.4 onwards, the filechooser which opens when you send the intent for picking up an image returns a relative uri, since it shows not only the files that are stored in your device but also the ones stored in the cloud. So, it could be happening that you're getting a relative URI and when you query for it's location on the device you're getting null, since the ContentResolver doesn't have the path of that file.
If that's the case (Actually even if you're not, since you should develop your app with compatibility for Android's new versions) i'd recommend you to use Content Resvolver to open a InputStream to get the file (openInputStream(Uri), since it will allow you to fetch a file from any location (both local and cloud).
I hope it helps :)
Well, here is how i do in my live wallpaper (Noiraude, have a look :P )
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch (requestCode) {
case 100:
if (resultCode == RESULT_OK) {
Uri selectedImage = imageReturnedIntent.getData();
#SuppressWarnings("unused")
InputStream imageStream = null;
try {
imageStream = getContentResolver().openInputStream(
selectedImage);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
sharedPreferences = getSharedPreferences("NLP_settings", 0);
Editor editor = sharedPreferences.edit();
editor.putString("key_bit", getPath(selectedImage));
editor.commit();
restartThis();
}
}
}
public String getPath(Uri uri) {
// just some safety built in
if (uri == null) {
return null;
}
// try to retrieve the image from the media store first
// this will only work for images selected from gallery
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
if (cursor != null) {
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
// this is our fallback here
return uri.getPath();
}