I have implemented image cropping in my app using android intent like below:
CropIntent = new Intent("com.android.camera.action.CROP");
I have received the cropped image and displayed on my UI but I want to perform further use cases like upload the cropped image uri. The problem is that no uri is returned in activity.
Here's my crop image intent snippet:
galleryFAB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d(TAG, "Gallery Btn Clicked");
selectFromGallery();
}
});
private void selectFromGallery() {
galleryIntent = new Intent(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("image/*");
startActivityForResult(Intent.createChooser(galleryIntent, "Choose From"), 2);
}
my code in activity result method:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
InputStream inputStream;
if (requestCode == 2 && resultCode == RESULT_OK){
if (data != null){
cropImageUri = data.getData();
userImage.setImageURI(cropImageUri);
try {
originalBitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), cropImageUri);
inputStream = getContentResolver().openInputStream(data.getData());
originalBitmap = BitmapFactory.decodeStream(inputStream);
Log.d(TAG, "Original bitmap byte count is:\t" + originalBitmap.getByteCount());
resizedBitmap = getResizedBitmap(originalBitmap, 200);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
resizedBitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
Log.d(TAG, "Resized bitmap byte count is:\t" + resizedBitmap.getByteCount());
try {
File file = saveBitmap("avatar_image");
upLoadFile(file);
} catch (IOException ex) {
ex.printStackTrace();
}
byte[] bytes = stream.toByteArray();
/**
* For Shared Preferences
* **/
encodedImage = Base64.encodeToString(bytes, Base64.DEFAULT);
imagePrefs = getSharedPreferences("ImagePrefs", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = imagePrefs.edit();
editor.putString("image_user", encodedImage).commit();
upLoadBytes(bytes);
} catch (IOException e) {
e.printStackTrace();
}
cropImage();
}
} else if (requestCode == PERM_CODE){
if (data != null){
//I want to get the cropped image uri here but unable to. Have tried converting the bitmap rcvd here to uri but in activity, ntn is returned. kindly guide me
Bundle bundle = data.getExtras();
originalBitmap = bundle.getParcelable("data");
userImage.setImageBitmap(resizedBitmap);
}
}
}
my crop image function:
private void cropImage() {
try {
CropIntent = new Intent("com.android.camera.action.CROP");
CropIntent.setDataAndType(cropImageUri, "image/*");
CropIntent.putExtra("crop", true);
CropIntent.putExtra("outputX", 200);
CropIntent.putExtra("outputY", 200);
CropIntent.putExtra("aspectX", 1);
CropIntent.putExtra("aspectY", 1);
CropIntent.putExtra("scale", true);
CropIntent.putExtra("return-data", true);
startActivityForResult(CropIntent, PERM_CODE);
} catch (ActivityNotFoundException ex){
}
}
Can anyone say how to get the output uri? Thanks.
If the cropped image is showing in an ImageView, follow this link to save it to device storage, then you can upload the file.
Related
This is the link which is used...android:select image from gallery then crop that and show in an imageview Problem is that images is not saving .When i am selecting picture it is coming in ImageView.but when I came out from this activity as well as from app ,it is not saving...Please help me.
Any help would be appreciated.
public class ImageSelecter extends Activity {
private final int GALLERY_ACTIVITY_CODE=200;
private final int RESULT_CROP = 400;
public ImageView imageView;
// static String picturePath;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView)findViewById(R.id.img_photo);
Button btn_choose = (Button) findViewById(R.id.btn_select_image);
btn_choose.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//Start Activity To Select Image From Gallery
Intent gallery_Intent = new Intent(getApplicationContext(), GalleryUtil.class);
startActivityForResult(gallery_Intent, GALLERY_ACTIVITY_CODE);
// break;
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GALLERY_ACTIVITY_CODE) {
if(resultCode == Activity.RESULT_OK){
GalleryUtil.picturePath = data.getStringExtra("picturePath");
//perform Crop on the Image Selected from Gallery
performCrop(GalleryUtil.picturePath);
}
}
if (requestCode == RESULT_CROP ) {
if(resultCode == Activity.RESULT_OK){
Bundle extras = data.getExtras();
Bitmap selectedBitmap = extras.getParcelable("data");
// Set The Bitmap Data To ImageView
imageView.setImageBitmap(selectedBitmap);
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
}
}
}
private void performCrop(String picUri) {
try {
//Start Crop Activity
Intent cropIntent = new Intent("com.android.camera.action.CROP");
// indicate image type and Uri
File f = new File(picUri);
Uri contentUri = Uri.fromFile(f);
cropIntent.setDataAndType(contentUri, "image/*");
// set crop properties
cropIntent.putExtra("crop", "true");
// indicate aspect of desired crop
cropIntent.putExtra("aspectX", 1);
cropIntent.putExtra("aspectY", 1);
// indicate output X and Y
cropIntent.putExtra("outputX", 280);
cropIntent.putExtra("outputY", 280);
// retrieve data on return
cropIntent.putExtra("return-data", true);
// start the activity - we handle returning in onActivityResult
startActivityForResult(cropIntent, RESULT_CROP);
}
// respond to users whose devices do not support the crop action
catch (ActivityNotFoundException anfe) {
// display an error message
String errorMessage = "your device doesn't support the crop action!";
Toast toast = Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT);
toast.show();
}
}
}
Supporting Class.
public class GalleryUtil extends Activity {
private final static int RESULT_SELECT_IMAGE = 100;
public static final int MEDIA_TYPE_IMAGE = 1;
private static final String TAG = "GalleryUtil";
String mCurrentPhotoPath;
File photoFile = null;
static String picturePath;
SharedPreferences sp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try{
//Pick Image From Gallery
Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_SELECT_IMAGE);
}catch(Exception e){
e.printStackTrace();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode){
case RESULT_SELECT_IMAGE:
if (resultCode == Activity.RESULT_OK && data != null && data.getData() != null) {
try{
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();
//return Image Path to the Main Activity
Intent returnFromGalleryIntent = new Intent();
returnFromGalleryIntent.putExtra("picturePath",picturePath);
setResult(RESULT_OK,returnFromGalleryIntent);
finish();
}catch(Exception e){
e.printStackTrace();
Intent returnFromGalleryIntent = new Intent();
setResult(RESULT_CANCELED, returnFromGalleryIntent);
finish();
}
}else{
Log.i(TAG, "RESULT_CANCELED");
Intent returnFromGalleryIntent = new Intent();
setResult(RESULT_CANCELED, returnFromGalleryIntent);
finish();
}
break;
}
}
}
Share preference cannot save the image, but you can save cropped image as a file, then save the file path to share preference as below.
SharedPreferences.Editor edit = sp.edit();
edit.putString("image_path", impage_path_string);
edit.commit();
Get image from ImageView and convert it to String base64 or if u your saving in database then make field blob
ImageView imageView=(ImageView)findViewById(R.id.profile_image);
Bitmap bitmap = ((BitmapDrawable)imageView.getDrawable()).getBitmap();
ByteArrayOutputStream stream=new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] image=stream.toByteArray();
String userimage= Base64.encodeToString(image, Base64.DEFAULT);
now save image in sharepreferences
SharedPreferences.Editor editor = getSharedPreferences(PREF_LOGIN, MODE_PRIVATE).edit();
editor.putString("USER_IMAGE",userimage);
editor.commit();
now get image from sharepreferences
String image=sharedPreferences.getString("USER_IMAGE", "IMAGE");
byte[] decodedString = Base64.decode(image, Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
imageView.setImageBitmap(decodedByte);
now for
start activity
Intent intent = new Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.INTERNAL_CONTENT_URI);
intent.setType("image/*");
intent.putExtra("crop", "true");
intent.putExtra("scale", true);
intent.putExtra("outputX", 256);
intent.putExtra("outputY", 256);
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
intent.putExtra("return-data", true);
startActivityForResult(intent, 1);
now for setimage to image view
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
Toast.makeText(getApplicationContext(),"ddddd",Toast.LENGTH_LONG).show();
final Uri imageUri = data.getData();
final InputStream imageStream = getContentResolver().openInputStream(imageUri);
final Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);
imageUser.setImageBitmap(selectedImage);
} catch (FileNotFoundException e) {
Toast.makeText(getApplicationContext(),e.toString(),Toast.LENGTH_LONG).show();
}
I have task to capture image from camera and send that image to crop Intent. following is the code i have written
for camera capture
Intent captureIntent = new Intent(
MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(captureIntent, CAMERA_CAPTURE);
In on Activity result
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == CAMERA_CAPTURE) {
// get the Uri for the captured image
picUri = data.getData(); // picUri is global string variable
performCrop();
}
}
}
public void performCrop() {
try {
Intent cropIntent = new Intent("com.android.camera.action.CROP");
cropIntent.setDataAndType(picUri, "image/*");
cropIntent.putExtra("crop", "true");
cropIntent.putExtra("aspectX", 3);
cropIntent.putExtra("aspectY", 2);
cropIntent.putExtra("outputX", 256);
cropIntent.putExtra("outputY", 256);
cropIntent.putExtra("return-data", true);
startActivityForResult(cropIntent, CROP_PIC);
} catch (ActivityNotFoundException anfe) {
String errorMessage = "Your device doesn't support the crop action";
Toast toast = Toast.makeText(getApplicationContext(), errorMessage,
Toast.LENGTH_SHORT);
toast.show();
}
}
I am getting different behaviours on different devices
In some devices i am getting error "couldn't find item".
In some devices after capturing image activity stuck and doesn't go ahead
I have also tried this
Please tell me the Right way to do this
You can by calling the intent like below:
int REQUEST_IMAGE_CAPTURE = 1;
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(android.os.Environment.getExternalStorageDirectory(), "temp.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
((Activity) context).startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);
And in your activity inside OnActivityResult you get the path like this:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == REQUEST_IMAGE_CAPTURE) {
File f = new File(Environment.getExternalStorageDirectory().toString());
for (File temp : f.listFiles()) {
if (temp.getName().equals("temp.jpg")) {
f = temp;
break;
}
}
try {
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
Bitmap bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(),
bitmapOptions);
Matrix matrix = new Matrix();
matrix.postRotate(-90);
Bitmap rotatedBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
rotatedBitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
byte[] attachmentBytes = byteArrayOutputStream.toByteArray();
String attachmentData = Base64.encodeToString(attachmentBytes, Base64.DEFAULT);
String path = android.os.Environment
.getExternalStorageDirectory()
+ File.separator
+ "CTSTemp" + File.separator + "default";
f.delete();
ESLogging.debug("Bytes size = " + attachmentBytes.length);
ESLogging.debug("FilePath = " + path);
OutputStream outFile = null;
File file = new File(path, String.valueOf(System.currentTimeMillis()) + ".jpg");
try {
outFile = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 85, outFile);
outFile.flush();
outFile.close();
} catch (FileNotFoundException e) {
ESLogging.error("FileNotFoundException while uploading new attachment in class HomeActivity", e);
e.printStackTrace();
} catch (IOException e) {
ESLogging.error("IOException while uploading new attachment in class HomeActivity", e);
e.printStackTrace();
} catch (Exception e) {
ESLogging.error("Exception while uploading new attachment in class HomeActivity", e);
e.printStackTrace();
}
} catch (Exception e) {
ESLogging.error("Exception while uploading new attachment in class HomeActivity", e);
e.printStackTrace();
}
}
}
}
//Declare this in class
private static int RESULT_LOAD_IMAGE = 1;
String picturePath="";
// write in button click event
Intent i = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
//copy this code in after onCreate()
#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();
ImageView imageView = (ImageView) findViewById(R.id.img); //place imageview in your xml file
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
}
write the following permission in manifest file
1.read external storage
2.write external storage
try this tutorial http://www.androidhive.info/2013/09/android-working-with-camera-api/ this will help you
I've an form that user can choose image from gallery or take an image . It works fine when user take an image but it's not working properly when user choose an image from gallery and then I ask for an intent for cropping the image .
On emulator cropping image from gallery works find but on 2 phones that i've tested , when I choose the cropping application , the cropping application crashes or if it not crached , it doesn't work and show the image on imageView .
This is my code :
final int PIC_CROP = 2;
final int CAMERA_CAPTURE = 1;
final int PICK_FROM_FILE = 3;
private Uri picUri;
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_CAPTURE && resultCode == RESULT_OK) {
picUri = data.getData();// get image URI
performCrop();
} else if (requestCode == PIC_CROP) {// crop and compress image
if (resultCode != RESULT_OK)
return;
Bundle extras = data.getExtras();
Bitmap thePic = extras.getParcelable("data");
FileOutputStream out = null;
ByteArrayOutputStream bao = new ByteArrayOutputStream();
double width = thePic.getWidth();
double height = thePic.getHeight();
double ratio = 650 / width;
int newheight = (int) (ratio * height);
thePic = Bitmap.createScaledBitmap(thePic, 650, newheight, true);
try {
out = new FileOutputStream(file);
thePic.compress(Bitmap.CompressFormat.JPEG, 295, out);
thePic.compress(Bitmap.CompressFormat.JPEG, 295, bao);
byte[] ba = bao.toByteArray();
switch (whichimg) {
case 1:
simg1 = Base64.encodeBytes(ba);
break;
} catch (Exception e) {
}
}
}
if (item == 0) {// take photo
Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(captureIntent, CAMERA_CAPTURE);
alert.dismiss();
} else if (item == 1) {// photo from gallery
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(
Intent.createChooser(intent, (getString(R.string.choosephototo))),
CAMERA_CAPTURE);
alert.dismiss();
}
this is the cropping codes :
private void performCrop() {
try {
Intent cropIntent = new Intent("com.android.camera.action.CROP");
cropIntent.setDataAndType(picUri, "image/*");
cropIntent.putExtra("crop", "true");
//cropIntent.putExtra("aspectX", 1);
//cropIntent.putExtra("aspectY", 1);
//cropIntent.putExtra("outputX", 356);
//cropIntent.putExtra("outputY", 256);
cropIntent.putExtra("return-data", true);
startActivityForResult(cropIntent, PIC_CROP);
} catch (ActivityNotFoundException anfe) {
MyToast.makeText(NewAdd2.this, DariGlyphUtils.reshapeText(getString(R.string.devicecouldcop)));
}
}
Could you help me ? Why it is not working fine ?
thanks
Try Below link for your Question, it will Work
may Problem in your performCrop() Method
Link For Crop
I used this code to use android's built in image crop tools. My code is the following
public void takePicture(){
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null){
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, MediaStore.Images.Media.EXTERNAL_CONTENT_URI.toString());
takePictureIntent.putExtra("crop", "true");
takePictureIntent.putExtra("aspectX", 0);
takePictureIntent.putExtra("aspectY", 0);
takePictureIntent.putExtra("outputX", 200);
takePictureIntent.putExtra("outputY", 150);
takePictureIntent.putExtra("return-data", true);
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data){
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
imageViewImage.setImageBitmap(imageBitmap);
}
}
takePicture is called inside a click listener for a Button. What is done is I can open android camera take the picture and when hitting save the image is saved on my imageView. But no cropping activity appears, plus the image on imageView looks awfull. The quality is like it's pixelated. Am I doing something wrong? I used a Samsung galaxy tab 3 to test my app
EDIT using the answer bellow...Stil not working
protected void onActivityResult(int requestCode, int resultCode, Intent data){
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Log.d("onActivityResult", "Inside on activity for result");
Bitmap imageBitmap = (Bitmap) extras.get("data");
imageViewImage.setImageBitmap(imageBitmap);
fileUri = getImageUri(this, imageBitmap);χ
cropImage();
}else if (requestCode == REQUEST_IMAGE_CROP && resultCode == RESULT_OK){
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap)extras.get("data");
imageViewImage.setImageBitmap(imageBitmap);
}
}
public void takePicture(){
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null){
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
public void cropImage() {
try {
Intent cropIntent = new Intent("com.android.camera.action.CROP");
cropIntent.setDataAndType(fileUri, "image/*");
cropIntent.putExtra("crop", "true");
cropIntent.putExtra("aspectX", 1);
cropIntent.putExtra("aspectY", 1);
cropIntent.putExtra("outputX", 128);
cropIntent.putExtra("outputY", 128);
cropIntent.putExtra("return-data", true);
startActivityForResult(cropIntent, REQUEST_IMAGE_CROP);
}
// respond to users whose devices do not support the crop action
catch (ActivityNotFoundException anfe) {
// display an error message
String errorMessage = "Whoops - your device doesn't support the crop action!";
Toast toast = Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT);
toast.show();
}
}
public Uri getImageUri(Context inContext, Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
return Uri.parse(path);
}
LocCat here
You can try this.
private void doCrop(Uri picUri) {
try {
Intent cropIntent = new Intent("com.android.camera.action.CROP");
cropIntent.setDataAndType(picUri, "image/*");
cropIntent.putExtra("crop", "true");
cropIntent.putExtra("aspectX", 1);
cropIntent.putExtra("aspectY", 1);
cropIntent.putExtra("outputX", 128);
cropIntent.putExtra("outputY", 128);
cropIntent.putExtra("return-data", true);
startActivityForResult(cropIntent, CROP_PIC_REQUEST_CODE);
}
// respond to users whose devices do not support the crop action
catch (ActivityNotFoundException anfe) {
// display an error message
String errorMessage = "Whoops - your device doesn't support the crop action!";
Toast toast = Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT);
toast.show();
}
}
Get Uri from bitmap
public Uri getImageUri(Context inContext, Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
return Uri.parse(path);
}
Declare
final int CROP_PIC_REQUEST_CODE = 1;
Than simply
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CROP_PIC_REQUEST_CODE) {
if (data != null) {
Bundle extras = data.getExtras();
Bitmap bitmap= extras.getParcelable("data");
yourImageView.setImageBitmap(bitmap);
}
}
}
I am uploading High resolution and big image on Server.
I am using API that accept image in Base64 converted String.
I am converting Image into Base64 String and uploading to server but if Image is big then it gives OutOfMemory Exception.
can any body suggest me how to solve this.
This is the function where i am converting myBitmap (Bitmap to upoload) in Base64 Encoded String to send on server.
I don't want to compress image.
if(myBitmap!=null){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
myBitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos); //bm is the bitmap object
byte[] b = baos.toByteArray();
// I am passing encodedImg as image parameter.
String encodedImg = new String(Base64.encodeBase64(b));
try{
baos.close();
baos = null;
b = null;
}
catch (Exception e) {
e.printStackTrace();
}
}
// Below code is to open camera/gallery to select Image
btnCamera.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
String fileName = "profile.jpg";
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, fileName);
values.put(MediaStore.Images.Media.DESCRIPTION, "Image capture by camera");
imageUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
intent.putExtra("crop", "true");
intent.putExtra("aspectX", 3);
intent.putExtra("aspectY", 4);
intent.putExtra("outputX", 480);
intent.putExtra("outputY", 640);
intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
intent.putExtra("noFaceDetection",true);
startActivityForResult(intent, 1);
a.dismiss();
}
});
btnGalary.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.putExtra("crop", "true");
intent.putExtra("aspectX", 3);
intent.putExtra("aspectY", 4);
intent.putExtra("outputX", 480);
intent.putExtra("outputY", 640);
intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
intent.putExtra("noFaceDetection",true);
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Gallery"),2);
a.dismiss();
}
});
//My onActivityResult
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case 1:
if (resultCode == RESULT_CANCELED)
break;
else if (resultCode == RESULT_OK) {
try{
long imageId=ContentUris.parseId(imageUri);
myBitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);
isImageChanged = true;
profilePic.setScaleType(ScaleType.CENTER_CROP);
profilePic.setImageBitmap(myBitmap);
break;
}
catch(Exception e){
e.printStackTrace();
}
}
case 2:
if (resultCode == RESULT_CANCELED)
break;
try {
Uri imageUri = data.getData();
long imageId=ContentUris.parseId(imageUri);
myBitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);
profilePic.setScaleType(ScaleType.CENTER_CROP);
isImageChanged = true;
profilePic.setImageBitmap(myBitmap);
} catch (Exception e) {
e.printStackTrace();
}
break;
}
}
Probably you might be getting an exception on
byte[] b = baos.toByteArray();
To handle that you want to consider recycling your images.
Also, using Multipart is considered a better option, since you are using Base64 you might want to ponder on Jen's Post too.
One more suggestion is, if you are on API level 11 or more then you may consider using:
android:largeHeap="true"
Which will help you to carry out your conversions and processing safely(Provided that you are not leaking any variable). For more information on this, see the documentation on Application.
Let me know if you still face any issues.