Android convert image from gallery into base64 result in OutOfMemory Exception - java

I would like to load image from gallery and then convert it into base64.
This does not sound so difficult. So i dod it this way:
first of all open gallery and choose picture:
picteureBtn.setOnClickListener(new View.OnClickListener() {
private Uri imageUri;
public void onClick(View view) {
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
});
second onActivityResult:
#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]);
picturePath = cursor.getString(columnIndex);
cursor.close();
}
}
and for the end way i want to decode my image which is at picutrePath
String b64;
StringEntity se;
String entityContents="";
if (!picturePath.equals("")){
Bitmap bm = BitmapFactory.decodeFile(picturePath);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] b = baos.toByteArray();
b64=Base64.encodeToString(b, Base64.DEFAULT);
}
Unfortunatly I get :
06-24 16:38:14.296: E/AndroidRuntime(3538): FATAL EXCEPTION: main
06-24 16:38:14.296: E/AndroidRuntime(3538): java.lang.OutOfMemoryError
06-24 16:38:14.296: E/AndroidRuntime(3538): at java.io.ByteArrayOutputStream.toByteArray(ByteArrayOutputStream.java:122)
Can anyone point me where I am doing mistake?

I'd suggest to change
Bitmap bm = BitmapFactory.decodeFile(picturePath);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100, baos);
//added lines
bm.recycle();
bm = null;
//added lines
byte[] b = baos.toByteArray();
b64=Base64.encodeToString(b, Base64.DEFAULT);
That way, you're not loading the Bitmap twice into your app's memory.

There are a lot of articles talking about this, basically you will need to calculate the dimensions before trying to decode it into a Bitmap have a look at the BitmapFactory class. I have an alternative solution for you, since you are picking a picture from the gallery, you can can get the Bitmap in activityForResult, like this:
Bitmap image = (Bitmap) data.getExtras().get("data");
and you can start your Intent for getting the images like:
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, RESULT_LOAD_IMAGE);

Related

Converting Bitmap into a valid Uri

I am developing an android app where user is selecting the image either from gallery or capture from camera. When user get the image from gallery i get the image uri then i pass this uri to other activity in string form. then in next activity i convert that string into uri and then uri into bitmap and set the image bitmap in imageview. Now when i capture the image from camera i get the image bitmap.
Now i want to convert this bitmap into valid uri and pass to next activity
if(requestCode==GET_FROM_GALLERY && resultCode == Activity.RESULT_OK) {
Uri selectedImage = data.getData();
System.out.println("URLLL "+selectedImage);
Log.v("PhotoActivity", "Captured image");
//Create intent
Intent intent = new Intent(MainActivity.this, FlagDisplayActivity.class);
intent.putExtra("URI", selectedImage.toString());
//Start Flag Display activity
startActivity(intent);
Log.v("PHOTO ACTIVITY", " uri: " + selectedImage);
}
if (requestCode == CAMERA_REQUEST && resultCode == Activity.RESULT_OK)
{
Bitmap photo = (Bitmap) data.getExtras().get("data");
Intent intent = new Intent(MainActivity.this, FlagDisplayActivity.class);
intent.putExtra("URI", photo);
//Start Flag Display activity
startActivity(intent);
}
This is how i get the uri in next activity
String imageUriString=getIntent().getStringExtra("URI");
final Uri selectedImage=Uri.parse(imageUriString);
and then convert the uri into bitmap like this
Bitmap bitmap = null;
try {
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(),
selectedImage);
} catch (IOException e) {
e.printStackTrace();
bitmap=StringToBitMap(imageUriString);
}
My main goal is to convert the bitmap into uri
You write your Bitmap into the local Cache of the Application and retrieve it from there.
Bitmap photo = (Bitmap) data.getExtras().get("data");// Get the Bitmap
val file = File(context.cacheDir,"CUSTOM NAME") //Get Access to a local file.
file.delete() // Delete the File, just in Case, that there was still another File
file.createNewFile()
val fileOutputStream = file.outputStream()
val byteArrayOutputStream = ByteArrayOutputStream()
photo.compress(Bitmap.CompressFormat.PNG,100,byteArrayOutputStream)
val bytearray = byteArrayOutputStream.toByteArray()
fileOutputStream.write(bytearray)
fileOutputStream.flush()
fileOutputStream.close()
byteArrayOutputStream.close()
val URI = file.toURI()
Now you can send the URI to another Activity as a String and retrieve the URI from the String and get the Bitmap from the URI.
Intent intent = new Intent(MainActivity.this, FlagDisplayActivity.class);
intent.putExtra("URI", URI.toString());
//Start Flag Display activity
startActivity(intent);
Provide the path of image it will provide you image uri
Uri selectedImageURI = data.getData();
File imageFile = new File(getRealPathFromURI(selectedImageURI));
Uri yourUri = Uri.fromFile(f);
Use the following function so you will get image
private String getRealPathFromURI(Uri contentURI) {
String result;
Cursor cursor = getContentResolver().query(contentURI, null, null, null, null);
if (cursor == null) { // Source is Dropbox or other similar local file path
result = contentURI.getPath();
} else {
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
result = cursor.getString(idx);
cursor.close();
}
return result;
}
Try this:
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
imageView.setImageBitmap(bitmap);

I don't know how to set a pic, chosen from local library

OK, so here is what I want to do in this android activity:
Press the button that says "choose pic"
Use intent or whatever, and go to choose a pic from your local photo library
Once you have chosen the pic, go to this activity
And this time, the image view below would be set (it will be the picture you've chosen)
I have read this q&a and tried the code below, in the activity, but it didnt work out.
android pick images from gallery
*for the last line I couldn't figure out what to write, I just wanted to set the exact picture
public void choosepic (View v){
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
Intent pickIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
pickIntent.setType("image/*");
Intent chooserIntent = Intent.createChooser(getIntent, "Select Image");
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[] {pickIntent});
startActivityForResult(chooserIntent, PICK_IMAGE);
foodpic.setpic
}
As your code says image cannot be set from the method where you launch the intent.
Override method with name onActivityResult() and use the following code in that method
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE && resultCode == RESULT_OK && data != null) {
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 imageView = (ImageView) findViewById(R.id.imgView);
Bitmap bmp = null;
try {
bmp = getBitmapFromUri(selectedImage);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
imageView.setImageBitmap(bmp);
}
Hope this helps.

android studio, how to save on save,change DATA

I have been making paint app
it has a save option and load, but every time I save another image go to gallery
i want to 'save on save' option too, to load image change and save on it.
the code save:
drawView.setDrawingCacheEnabled(true);
//attempt to save
String ima= MediaStore.Images.Media.insertImage(
getContentResolver(), drawView.getDrawingCache(),
UUID.randomUUID().toString() + ".png", "drawing");
//feedback
if (ima != null) {
Toast savedToast = Toast.makeText(getApplicationContext(),
"Drawing saved to Gallery!", Toast.LENGTH_SHORT);
savedToast.show();
} else {
Toast unsavedToast = Toast.makeText(getApplicationContext(),
"Oops! Image could not be saved.", Toast.LENGTH_SHORT);
unsavedToast.show();
}
drawView.destroyDrawingCache();
}
saveDialog.show();
the load code:
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
});
saveDialog.show();
}
}
#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 = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
columnIndex = cursor.getColumnIndex(filePathColumn[0]);
temp = cursor.getString(columnIndex);
cursor.close();
a= BitmapFactory.decodeFile(temp);
Drawable d = new BitmapDrawable(getResources(), a);
drawView.setBackgroundColor(Color.WHITE);
drawView.startNew();
drawView.setBackground(d);
Rather than trying to have a save on save method, perhaps try instead of loading a default image you load the image you would like to edit. The file path exists since you are saving them in the drawable area and you are able to access the images in your drawable.

Capturing Image from camera and displaying it in another activity in android

I am developing an application in which i want to capture the image from the camera and display it in another activity in an image view, my problem is that able to capture the image but after capturing i am redirected to first activity instead to second one.
Here is my Code..
PictureOptions.java
public void buttonCameraOpen(View view)
{
// create Intent to take a picture and return control to the calling application
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE); // create a file to save the image
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file name
// start the image capture Intent
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
}
private static Uri getOutputMediaFileUri(int type){
return Uri.fromFile(getOutputMediaFile(type));
}
/** Create a File for saving an image or video */
private static File getOutputMediaFile(int type){
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "Easy Heal");
// This location works best if you want the created images to be shared
// between applications and persist after your app has been uninstalled.
// Create the storage directory if it does not exist
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
Log.d("MyCameraApp", "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE){
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"IMG_"+ timeStamp + ".jpg");
} else {
return null;
}
return mediaFile;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Bitmap selectedphoto = null;
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE && resultCode == RESULT_OK && null!=data) {
// Image captured and saved to fileUri specified in the Intent
//selectedphoto = (Bitmap) data.getExtras().get("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 filePath = cursor.getString(columnIndex);
File f =new File(filePath);
String filename = f.getName();
cursor.close();
selectedphoto = BitmapFactory.decodeFile(filePath);
Intent intent = new Intent(PictureOptions.this,ShowImage.class);
//intent.putExtra("data", selectedphoto);
intent.setData( selectedImage );
startActivity(intent);
} else if (resultCode == RESULT_CANCELED) {
// User cancelled the image capture
} else {
// Image capture failed, advise user
}
}
PictureOptions.xml
<Button
android:id="#+id/buttonCameraOpen"
android:layout_width="fill_parent"
android:layout_height="72dp"
android:layout_weight="0.35"
android:onClick="buttonCameraOpen"
android:text="#string/button_camera_open" />
ShowImage.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_image);
ImageView imageview = (ImageView)findViewById(R.id.ImageShow);
Uri imageUri = getIntent().getData();
//Bitmap selectedphoto =(Bitmap)this.getIntent().getParcelableExtra("data");
imageview.setImageURI(imageUri);
}
ShowImage.xml
<ImageView
android:id="#+id/ImageShow"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
I finally found an awesome solution
This library is used to capture image from camera or select from gallery and return back image in File format in onActivityResult method, which can be used further in the application.
Use
EasyImage Library
Uri uriSavedImage=Uri.fromFile(new File("/sdcard/flashCropped.png"));
camera.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
startActivityForResult(camera, 1);
After clicking the image, check whether it exists or not. Then send the path to the image file to the next activity and display it via Bitmap.
Call the camera intent
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
then on activity for result use this
'case REQUEST_IMAGE_CAPTURE:
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
saveBitmap(imageBitmap);
mimageView1.setImageBitmap(imageBitmap);
mIntent.putExtra("ACTIVITY_CODE", 1);
startActivity(mIntent);
break;
the add this method in ur same class
public void saveBitmap(Bitmap bmp)
{
String file_path = Environment.getExternalStorageDirectory().getAbsolutePath() +"/DCIM";
try
{
File dir = new File(file_path);
if(!dir.exists())
dir.mkdirs();
File file = new File(dir, "time");
cameraUrl=file.getAbsolutePath();
FileOutputStream fOut = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.PNG, 100, fOut);
fOut.flush();
fOut.close();
}
catch (Exception e) {
Log.e("errr in ","inserting the image at parictular location");
}
}
then call this in ur another activity where u want the image
String valueC = getIntent().getExtras().getString("CAMERA");
Log.v("imageBitmap", ""+valueC);
Bitmap yourSelectedImageC = BitmapFactory.decodeFile(valueC);
mImgV_image.setImageBitmap(yourSelectedImageC);
I have same problem after spending 2 days finally i got the anwer
First activity
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK && data != null) {
Uri uri = data.getData();
Intent intent= new Intent(this,SecondActivity.class);
selfiSrc.putExtra("imgurl", uri );
startActivity(intent);
}
SecondActivity
Imageview iv_photo=(ImageView)findViewById(R.id.iv_photo);
Bundle extras= getIntent().getExtras();
if(extras!=null)
{
path = (Uri) extras.get("imgurl");
iv_photo.setImageURI(path);
}
Another way see my answer
Android - how can i transfer ImageView from one activity to another activity?

How to store images from sdcard in avd to database in android?

I am new to Android. I have just created an AVD with 256 MB android-SDcard in it in Android 2.1. And I have inserted two images into it. I have done this using the DDMS perspective. And the images are now stored into a folder 100ANDRO in the DCIM folder of SDcard. Now I want to create an application that allows the user to select the images through browsing the folders and need to save the corresponding image to the database android-sqlite.
Can someone help me to find an appropriate method for this? Thanks in advance.
I have found one method for this.
I have created a button for UPLOAD and on the click action I have set like this.
upload.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v) {
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, 1);
}
});
And I have overrided this method along with the same class as below.
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case 1:
{
if (resultCode == RESULT_OK)
{
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();
Bitmap bitmap = BitmapFactory.decodeFile(filePath);
imgView.setImageBitmap(bitmap);
int size = bitmap.getWidth() * bitmap.getHeight();
ByteArrayOutputStream out = new ByteArrayOutputStream(size);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
try {
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();}
String bb = out.toString();
byte[] x = out.toByteArray();
image_value.setTag(x);
image_value.setText(filePath);
}catch(Exception e)
{}
}
}
}
Here image_value represents a hidden text view in the xml file.
I have passed the value of the image location and bytes as text view's value and tag.
And later on I have saved this bytes into the database for later display. Its working fine.
Thanks to all.

Categories

Resources