URI from OnActivityResult with imageview - android

In my app, a user click a button to open the Choser to choose a pic. On my activity result the code is
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE_REQUEST_CODE) {
Uri selectedImageUri = data.getData();
if(selectedImageUri!=null){
imageviewTest.setImageURI(selectedImageUri)
}else{
}
}
}
}
The image is not displayed. I am wondering why? I noticed some people on this forum pass this value to contentresolver, why is that? Shouldn't the path be sufficient?
Thanks

public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE_REQUEST_CODE) {
BitmapFactory.Options bfOptions =new BitmapFactory.Options();
Uri selectedImage = data.getData();
if(selectedImage!=null){
String galleryImatePath = getRealPathFromURI(selectedImage);
try{
bfOptions.inDither=false; //Disable Dithering mode
bfOptions.inPurgeable=true; //Tell to gc that whether it needs free memory, the Bitmap can be cleared
bfOptions.inInputShareable=true; //Which kind of reference will be used to recover the Bitmap data after being clear, when it will be used in the future
bfOptions.inSampleSize=5;
bfOptions.inTempStorage=new byte[32 * 1024];
InputStream stream = getContentResolver().openInputStream(selectedImage);
final Bitmap myImage = BitmapFactory.decodeStream(stream, null , bfOptions);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
myImage.compress(Bitmap.CompressFormat.JPEG, 100, bos);
bitmapdata = bos.toByteArray();
imageviewTest.setImageBitmap(myImage)
}else{
}
}
}
}
public String getRealPathFromURI(Uri contentUri) {
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}

Related

How to get address from gallery in android

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.

Picasso not loading image from gallery

I've tried every answer I've found for this issue without success.
My users choose an image from their gallery to be displayed in an ImageView using Picasso, but it never get's loaded into the imageview.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode,resultCode,data);
if(resultCode == RESULT_OK){
if(requestCode == SELECT_PICTURE){
String selectedImageURI = data.getData().getPath();
File imageData = new File(String.valueOf(selectedImageURI));
//selectedImagePath = getPath(selectedImageURI);
if(!image1_exists){
Picasso.with(MemoriesActivity.this).load(imageData).noPlaceholder().centerCrop().fit().into(image1);
}
else if(!image2_exists){
//This is executed
Picasso.with(MemoriesActivity.this).load(imageData).noPlaceholder().centerCrop().fit().into(image2);
}
else if(!image3_exists){
//Picasso.with(MemoriesActivity.this).load(imageData).centerCrop().fit().into(image3);
}
}
}
}
public void addPhoto(View v){
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Picture"), SELECT_PICTURE);
}
I can't find any explainable cause for this except something must be wrong with onActivityResult together with Picasso, because I load images using exactly the same Picasso build/method when fetching images from my backend.
EDIT SOLUTION
public void attachImage(Uri uri, int imageIndex) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 0;
InputStream stream;
try {
stream = getContentResolver().openInputStream(uri);
Bitmap bitmap = BitmapFactory.decodeStream(stream);
Bitmap image_scaled = Bitmap.createScaledBitmap(bitmap, 800, 800 * bitmap.getHeight() / bitmap.getWidth(), false);
if (imageIndex == 0) {
uploadImage(image_scaled, "image1");
handler.get(imageIndex).loadImageFromUri(this,(ImageView) findViewById(R.id.image1),uri);
handler.get(imageIndex).loadEnlargedImageFromUri(this,image1_full,uri);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
So I created that method (it's under construction, but the solution remains the same) and calls it like this in onActivityResult :
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
Uri selectedImage = data.getData();
int imageIndex = getFirstNonExistingImage();
if (imageIndex == 0) {
attachImage(selectedImage,imageIndex);
}
}
}
}
I load the URI with a custom Picasso class (handler.loadImageFromUri), but same principle.
Solved by creating an external method and executing that inside onActivityResult instead. No idea why, but it worked.
get real path from URI and set it to Picasso.
Uri selectedImage = data.getData();
imagePath = getRealPathFromURI(this, selectedImage);
public String getRealPathFromURI(Context context, Uri contentUri) {
Cursor cursor = null;
try {
String[] proj = {MediaStore.Images.Media.DATA};
cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} finally {
if (cursor != null) {
cursor.close();
}
}
}
You dont need to make cursor query with picasso.
With picasso you just need to write one line of code I have extended it for better understanding :-
//Get image Uri
Uri selectedImageURI = data.getData();
//Load image from picked Uri
Picasso.with(MainActivity1.this).load(selectedImageURI).noPlaceholder().centerCrop().fit()
.into((ImageView) findViewById(R.id.imageView1));

Base64 encode is becoming a piece of the image

I'm trying to get an image from the Gallery and send it to a server.
I do get an base64 encoded string but it's a thin line, not the whole image.
For example, I used Motobit to decode this random image. The base64 string I got
works fine. But the encoded string that I get from my app for the same image is really smaller and when you convert into an image it becomes this.
Here is my code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_profile);
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, SELECT_PHOTO);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch(requestCode) {
case SELECT_PHOTO:
if(resultCode == RESULT_OK){
try {
Uri selectedImage = imageReturnedIntent.getData();
String imageStream = getRealPathFromURI(context, selectedImage);
Bitmap bitmap = BitmapFactory.decodeFile(imageStream);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
byte[] byteArray = byteArrayOutputStream .toByteArray();
String encodedString = Base64.encodeToString(byteArray, Base64.DEFAULT);
Log.e(LOG_TAG, encodedString);
}catch (Exception e){
e.printStackTrace();
}
}
}
}
public String getRealPathFromURI(Context context, Uri contentUri) {
Cursor cursor = null;
try {
String[] proj = { MediaStore.Images.Media.DATA };
cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} finally {
if (cursor != null) {
cursor.close();
}
}
}
What is making my encodedString becomes only a piece of the image? Thanks!
Maybe the string is correct but the Log method has a character limit.

Android bitmap.recycle() doesn't work

I'm trying to load an image from the gallery, but toSave.recycle() doesn't work.
I mean when toSave.recycle() is called the screen becomes white, the app doesn't crash but the image is not shown.
Do you have any suggestions?
Here the code:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == LOAD_IMAGE_RESULT && resultCode == RESULT_OK && data != null) {
Uri pickedImage = data.getData();
String[] filePath = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(pickedImage, filePath, null, null, null);
cursor.moveToFirst();
String imagePath = cursor.getString(cursor.getColumnIndex(filePath[0]));
Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
postImage.setImageBitmap(bitmap);
saveImage(bitmap);
cursor.close();
}
}
Here the method that converts bitmap image and save it in Firebase.
public void saveImage(Bitmap toSave){
if (toSave!=null) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
toSave.compress(Bitmap.CompressFormat.JPEG, 50, stream);
toSave.recycle();
byte[] byteArray = stream.toByteArray();
String imageString = Base64.encodeToString(byteArray, Base64.DEFAULT);
simplepostRef.child("image").setValue(imageString);
}
Thank you a lot!
bitmap.recycle() is working in your case. You just dont need to recycle the bitmap because you are showing this bitmap in a imageview.Have a look at the docs.

Code for fetching a picture (bitmap) from gallery not working

MY SOLUTION: Ok some good answers. This is what I came up with. Not sure to answer my own question or put it here for proper stackoverflowness so if anyone knows please share.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
switch (requestCode) {
case cameraData:
Bundle extras = data.getExtras();
bmp = (Bitmap) extras.get("data");
iv.setVisibility(View.VISIBLE);
break;
case SELECT_PICTURE:
Uri selectedImageUri = data.getData();
selectedImagePath = getPath(selectedImageUri);
File imgFile = new File(selectedImagePath);
bmp = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
break;
}
iv.setVisibility(View.VISIBLE);
iv.setImageBitmap(bmp);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 50, stream); // compress
byte[] ba = stream.toByteArray();
image_str = Base64.encodeBytes(ba);
}
}
//////////////////////////////////////////////////////////////////////////////////////////
OK I have a path to picture in my gallery. I want to take that picture and turn it into a bundle so I can 64 encode it to upload to my server. here is my onActivityResult. I have it working from taking a picture with the camera just not getting it from the gallery.
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK){
switch(requestCode){
case cameraData:
Bundle extras = data.getExtras();
bmp = (Bitmap) extras.get("data");
Log.e("picture","Take Picture");
break;
case SELECT_PICTURE:
Uri selectedImageUri = data.getData();
selectedImagePath = getPath(selectedImageUri);
Log.e("picture",selectedImagePath);
File imgFile = new File(selectedImagePath);
bmp = (Bitmap) BitmapFactory.decodeFile(imgFile.getAbsolutePath());
Bundle extras1 = ((Cursor) imgFile).getExtras();
// bmp = (Bitmap) extras1.get("data");
Log.e("picture","from Gallery");
break;
}
}
}
the base 64 code is not mine its from this site: http://blog.sptechnolab.com/2011/03/09/android/android-upload-image-to-server/
getPath:
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
Why would you want to turn the bitmap into a bundle? And why do you want to turn the file into a base64 String before you upload?
Here and here are examples that upload a file.
http://pastebin.com/3A5gMFsF
Seems to do what you want. Looks like when you get a file URI back you need to dig through some Content Resolvers to actually get the file itself.
Uri photoUri = data.getData();
if (photoUri != null)
{
try {
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(photoUri, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex);
cursor.close();
bMap_image = BitmapFactory.decodeFile(filePath);
ImageView img = (ImageView) findViewById(R.id.gallery1);
img.setImageBitmap(bMap_image);
Edit: The only difference I see between this version and your version is that this version doesn't convert the filePath into a File before calling BitMap.Decode. It calls BitmapFactory.decodeFile directly on the file path returned from the content resolover.
You can directly convert the bitmap to base64.
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.PNG, 0 /*ignored for PNG*/, bos);
byte[] bitmapdata = bos.toByteArray();
byte[] dataToUpload = Base64.encode(bitmapdata , DEFAULT);
To convert the bitmap to Bundle use bundle.putParcelable("dataToUpload", bitmap)
and retireve it using bundle.getParcelable("dataToUpload").

Categories

Resources