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

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").

Related

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.

Issue in Posting Image on php Server in android

I am working on a module in which user can upload the image to the server. To achieve this, I have to change selected image into Base64. After conversion, I have to use Json POST method to upload image, but every time application crashes and I am getting error in this line..
String ba1=Base64.encodeToString(ba,Base64.DEFAULT);
this is my code that I am trying, PLease have a look and let me what mistake I am doing here.
buttonLoadPicture.setOnClickListener( new View.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);
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));
ss = BitmapFactory.decodeFile(picturePath);
Log.d("value", ss.toString());
Bitmap bitmapOrg = BitmapFactory.decodeResource(getResources(),ss);
ByteArrayOutputStream bao = new ByteArrayOutputStream();
bitmapOrg.compress(Bitmap.CompressFormat.JPEG, 100, bao);
byte [] ba = bao.toByteArray();
String ba1=Base64.encodeToString(ba,Base64.DEFAULT);
encodeToString is not a function in BitmapFactory. You should encode to base64 in a different way. I would like to suggest this answer

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.

URI from OnActivityResult with imageview

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

Add large size images from gallery to my app

My app is crashed while adding large size images from my device gallery to my app. I had gone through some solutions like resizing, scaling etc but it didn't work out.
Following code part is executed when I select an image from gallery
protected void onActivityResult(int requestCode, int resultCode,
Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch(requestCode) {
case REQ_CODE_PICK_IMAGE:
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);
cursor.close();
//Convert Bitmap to Byte Array:-
Bitmap yourSelectedImage = BitmapFactory.decodeFile(filePath);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
yourSelectedImage.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
//Pass byte array into intent:-
Intent intent = new Intent(UserAccount.this,RetrieveImage.class);
intent.putExtra("picture", byteArray);
startActivity(intent);
} } }
RetrieveImage.java
Bundle extras = getIntent().getExtras();
byte[] byteArray = extras.getByteArray("picture");
Bitmap bmp = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
ImageView img = (ImageView) findViewById(R.id.imageView1);
img.setImageBitmap(bmp);
How can I solve this problem.
Use this for Scaling :
Bitmap ThumbImage = ThumbnailUtils.extractThumbnail(BitmapFactory.decodeFile(imagePath),
THUMBSIZE, THUMBSIZE);
InputStream stream = context.getContentResolver().openInputStream(imageUri);
stream = ctx.getContentResolver().openInputStream(imageUri);
Bitmap bitmap = BitmapFactory.decodeStream(stream, null, options);
stream.close();
Use above to get bitmap image from image uri create your options.
Try this code
File f = new File("getfile from media");
if(f.exists())
{
FileInputStream is = null;
try {
is = new FileInputStream(f);
} catch (FileNotFoundException e) {
Log.d("error: ", String.format(
"ShowPicture.java file[%s]Not Found", fileName));
return;
}
Bitmap bm = BitmapFactory.decodeStream(is, null, null);
pic.setImageBitmap(bm);
}

Categories

Resources