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
Related
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.
My Code works on all devices Android 4 till Android 6.x
But after I have updated my device on Android 7.0, the camera code does not work more. I get black screen !
I can make capture from camera but after that i get back screen if I want to crop the image
may be the crop funktion does not get the corect path of the bitmap
screen
any Idea? here is the code :
img = (ImageView) findViewById(R.id.imageView);
img_original = (ImageView) findViewById(R.id.imageView_original);
}
public void Capture(View view) {
Capture_Cam();
}
private void Capture_Cam() {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, 1);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1 && resultCode == RESULT_OK && data != null) {
picUri = data.getData();
try {
// bitmap2 = MediaStore.Images.Media.getBitmap(this.getContentResolver(), picUri); // bitmap2 = original before cur
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), Uri.parse("file://"+picUri));
img_original.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
performCrop();
} else if (requestCode == 2) {
bitmap2=(Bitmap) data.getExtras().get("data");
img.setImageBitmap(bitmap2);
}else{
super.onActivityResult(requestCode, resultCode, data);
}
}
private void performCrop(){
try {
Intent cropIntent = new Intent("com.android.camera.action.CROP");
//indicate image type and Uri
cropIntent.setDataAndType(picUri, "image/*");
cropIntent.putExtra("crop", "true");
cropIntent.putExtra("aspectX", 1);
cropIntent.putExtra("aspectY", 1);
cropIntent.putExtra("outputX", 100);
cropIntent.putExtra("outputY", 100);
cropIntent.putExtra("scale", true);
cropIntent.putExtra("return-data", true);
startActivityForResult(cropIntent, 2);
Toast toast = Toast.makeText(this, "Done", Toast.LENGTH_SHORT);
}
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();
}
}
}
I want to pick image from the gallery and use it in my App as Profile Picture. So far I've tried this.
Here's my InfoGet class. The loadImagefromGallery gets called on click.
public void loadImagefromGallery(View view) {
/* Intent galleryIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, RESULT_LOAD);*/
Intent gallery_Intent = new Intent(getApplicationContext(), GalleryUtil.class);
startActivityForResult(gallery_Intent, GALLERY_ACTIVITY_CODE);
}
#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){
String picturePath = data.getStringExtra("picturePath");
//perform Crop on the Image Selected from Gallery
performCrop(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
pro.setImageBitmap(selectedBitmap);
pro.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();
}
}
And here's my GalleryUtil code
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;
#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]);
String 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;
}
}
}
I need help can anyone just make some changes in the existing code. I do not want to rebuild anything from scratch. I want to optimise this image picker before I release the next update. The Existing code work okay for devices with decent amount of RAM like 1GB or so.
Please help me.
And also explain what you did and how it works. Thanks a LOT.
I did that method read images from path and solve this issue, maybe it help you:
public static Bitmap readBitmap(Uri selectedImage, int resizeFactor)
{
Bitmap bm = null;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = resizeFactor;
AssetFileDescriptor fileDescriptor = null;
try
{
fileDescriptor = context.getContentResolver().openAssetFileDescriptor(selectedImage, "r");
} catch (FileNotFoundException e)
{
e.printStackTrace();
} finally
{
try
{
bm = BitmapFactory.decodeFileDescriptor(fileDescriptor.getFileDescriptor(), null, options);
fileDescriptor.close();
} catch (IOException e)
{
e.printStackTrace();
}
}
return bm;
}
The atributes are Uri selectedImage and int resizeFactor;
on selectedImage you need to put a Path from image and on resizeFactor put a int number, Normally I use number 10, try with that or try with another one (down/up)
Now if you want to put on ImageView you can use that.
ImageView.setImageBitmap(readBitmap(Path, 10));
Later you need clear Bitmap content to avoid OutOfMemory, use that method:
public static void clearBitmap(Bitmap bm)
{
bm.recycle();
}
I do a crop on an image after it is captured by my camera - all working.
The image appears in my gallery all cropped and lovely - all working.
I assign the image after calling crop to a imageview using the uri - not working
Heres my code, i think my issue is that the uri is pointing to the old uncropped image in \storage\emulator\0... and the cropped goes straight to my gallery. How can i get cropped úí and the cropped image is in my gallery - How do i get the cropped image into my imageView
code:
private static final int PICK_IMAGE = 0;
private static final int PICK_IMAGE_FROM_GALLERY = 1;
private static final int CROP_IMAGE = 2;
private Uri uri;
.
.
.
btnPhotoCamera.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent camera=new Intent();
camera.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
//camera.putExtra("crop", "true");
File f=Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
uri = Uri.fromFile(new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),"myFile.jpg"));
camera.putExtra(MediaStore.EXTRA_OUTPUT, uri);
startActivityForResult(camera, PICK_IMAGE);
}
});
private void performCrop(Uri picUri)
{
//NEXUS 5 OS 5 is example of this branch
// take care of exceptions
try {
// call the standard crop action intent (the user device may not
// support it)
Intent cropIntent = new Intent("com.android.camera.action.CROP");
// indicate image type and Uri
cropIntent.setDataAndType(uri, "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
// retrieve data on return
cropIntent.putExtra("return-data", true);
// start the activity - we handle returning in onActivityResult
startActivityForResult(cropIntent, CROP_IMAGE);
}
// respond to users whose devices do not support the crop action
catch (ActivityNotFoundException anfe)
{//NOT TESTED AS HW DOES NOT GO HERE
Toast toast = Toast.makeText(this,"This device doesn't support the crop action! Exception: " + anfe.toString(),Toast.LENGTH_SHORT);
toast.show();
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
// TODO Auto-generated method stub
if (resultCode==RESULT_OK )
{
if(requestCode == PICK_IMAGE) //reply from camera
{
performCrop(uri); //crop the picture
}
if(requestCode == CROP_IMAGE) //reply from crop
{
Bitmap bmp = getBitmap(uri);
imgView.setImageBitmap(bmp);
}
}
}
private Bitmap getBitmap(Uri bitmap_uri) {
InputStream is=null;
try
{
is = this.getContentResolver().openInputStream(bitmap_uri);
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
return BitmapFactory.decodeStream(is);
}
}
Crop result will be in the date extra in onActivityResult as below:
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
if(requestCode == CROP_IMAGE && resultCode == RESULT_OK) //reply from crop
{
Bundle extras = data.getExtras();
if(extras != null ) {
Bitmap photo = extras.getParcelable("data");
FileOutputStream fOut = new FileOutputStream(tmpFile);
photo.compress(Bitmap.CompressFormat.JPEG, 75, fOut);
//etc
}
}
}
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);
}
}
}