Runtime Cropping an Image in android - android

I have already selected an image from SD card in my activity's ImageView using Intent.and now I want to show a fixed size moving Rectangle i.e. we have to use gesture and whatever portion of the image we want,then we are able to crop that.How can we do that?Its really tough for me to do?
Please help me in doing that?
Update-->I have been able to bring the rectangle and I m getting problem in cropping and saving that selected part.How to do this?

ok geetanjali. try this code this will open gallery and you can pick a photo to crop, it will store with name starts from apple, you can see cropped image in your activity
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
photoPickerIntent.putExtra("crop","true");
photoPickerIntent.putExtra(MediaStore.EXTRA_OUTPUT, getTempFile());
photoPickerIntent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
startActivityForResult(photoPickerIntent, 1);
}
private Uri getTempFile() {
if (isSDCARDMounted()) {
String f;
muri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(),
"apple_" + String.valueOf(System.currentTimeMillis()) + ".jpg"));
//File f = new File(Environment.getExternalStorageDirectory(),"titus1.jpg");
try {
f=muri.getPath();
} catch (Exception e) {
}
return muri;
} else {
return null;
}
}
private boolean isSDCARDMounted(){
String status = Environment.getExternalStorageState();
if (status.equals(Environment.MEDIA_MOUNTED))
return true;
return false;
}
protected void onActivityResult(int requestCode, int resultCode,
Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch (requestCode) {
case 1:
if (resultCode == RESULT_OK) {
String filePath= muri.getPath();
Log.e("path", "filePath");
Toast.makeText(this, filePath, Toast.LENGTH_LONG).show();
Bitmap selectedImage = BitmapFactory.decodeFile(filePath);
image = (ImageView)findViewById(R.id.image);
image.setImageBitmap(selectedImage);
}
}
}

Related

Android - Check button after taking picture using camera doesn't do anything

So.. I'm trying to choose a picture using both camera and gallery, then pass it to an external library to crop image.
The problem lies with saving image after taking it with the camera. I've managed to get the camera running and take an image with it, then it display the image and the default Android Ok and back button. The Ok button responds to touch (as touch effect can be seen) but it doesn't do anything.
Here's the code for getting the file ready to save
date = calendar.getTime();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("ddMMyyyyHHmmss");
dateString = simpleDateFormat.format(date);
dateBuilder = new StringBuilder().append(dateString).append(".jpg");
SAMPLE_CROPPED_IMAGE_NAME = dateBuilder.toString();
final String cameraDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/SamplePics/";
newDir = new File(cameraDir);
newDir.mkdirs();
This is the code for camera function
RelativeLayout.OnClickListener photoCameraWrapperHandler = new RelativeLayout.OnClickListener(){
#Override
public void onClick(View v) {
//Intent intent = new Intent(SignupStepThreeActivity.this, SignupStepFourActivity.class);
//startActivity(intent);
String cameraFile = SAMPLE_CROPPED_IMAGE_NAME;
newFile = new File(cameraFile);
try {
newFile.createNewFile();
}
catch (IOException e)
{
}
Uri outputFileUri = Uri.fromFile(newFile);
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
};
And here's the onActivityResult :
private static final int CAMERA_REQUEST = 1888;
private static final int REQUEST_SELECT_PICTURE = 0x01;
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == REQUEST_SELECT_PICTURE || requestCode == CAMERA_REQUEST) {
final Uri selectedUri = data.getData();
if (selectedUri != null) {
startCropActivity(data.getData());
} else {
Toast.makeText(SignupStepThreeActivity.this, R.string.toast_cannot_retrieve_selected_image, Toast.LENGTH_SHORT).show();
}
} else if (requestCode == UCrop.REQUEST_CROP) {
handleCropResult(data);
}
}
if (resultCode == UCrop.RESULT_ERROR) {
handleCropError(data);
}
}
Several updates before, it crashes when I click on camera button, I suspected it was because of I kind of take the uri of the image from storage but I haven't created the folder. Now I finally managed to get the camera running but not saving. The create folder part works tho..
public String getCamerPath(Context context) {
SharedPreferences prefs = context.getSharedPreferences("setCamerPath", 0);
String value = prefs.getString("getCamerPath", "");
return value;
}
public void setCamerPath(Context context, String value)
{
SharedPreferences prefs = context.getSharedPreferences("setCamerPath", 0);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("getCamerPath", value);
editor.commit();
}
Uri outputFileUri = Uri.fromFile(newFile);
setCamerPath(this, outputFileUri.getPath());
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == REQUEST_SELECT_PICTURE || requestCode == CAMERA_REQUEST) {
startCropActivity(getCamerPath(this));
} else if (requestCode == UCrop.REQUEST_CROP) {
handleCropResult(data);
}
}
if (resultCode == UCrop.RESULT_ERROR) {
handleCropError(data);
}
}
In the camera OnClickListener, I commented some stuffs like this :
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
//Uri outputFileUri = Uri.fromFile(newFile);
//cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
//setCamerPath(SignupStepThreeActivity.this, outputFileUri.getPath());
startActivityForResult(cameraIntent, CAMERA_REQUEST);
In my onActivityResult, I've modified a part of CAMERA_REQUEST :
else if (requestCode == CAMERA_REQUEST) {
Uri capturedImageUri = data.getData();
Bitmap bitmap;
if (capturedImageUri != null) {
startCropActivity(capturedImageUri);
} else {
Toast.makeText(SignupStepThreeActivity.this, R.string.toast_cannot_retrieve_selected_image, Toast.LENGTH_SHORT).show();
Bundle extras = data.getExtras();
bitmap = (Bitmap) extras.get("data");
Uri imageUri = getImageUri(SignupStepThreeActivity.this, bitmap);
startCropActivity(imageUri);
}
}
So basically as I've been reading around for the past 4 hours, data is Intent. It will always be not null BUT will not always contain Uri itself for the image. Because I need the Uri for a library I'm using, I use a method called getImageUri from another Stackoverflow answer.
public static 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);
}
Now the problem lies with bitmap image quality after taking the image, I'm going to tinker around with it and be back with an update.
This can also resolve the problem
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
Log.d("camera", "onSaveInstance");
// save file url in bundle as it will be null on screen orientation
// changes
outState.putParcelable("file_uri", fileUri);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
Log.d("camera", "onRestoreInstance");
// get the file url
fileUri = savedInstanceState.getParcelable("file_uri");
}

Unable to use intent for CAMERA

In my application ,on clicking Image View i want to start Camera which will capture image and display it in another image view.My code is given below:
//On clicking Camera
iv_camera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
});
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
if (data != null) {
Log.e("Result Code", String.valueOf(resultCode));
Bitmap photo = (Bitmap) data.getExtras().get("data");
Uri selectedImageUri = data.getData();
Log.e("ImageUri", String.valueOf(selectedImageUri));
String realPath = getRealPathFromURI(selectedImageUri);
Log.e("Real Path", realPath);
imgProfilePic.setImageBitmap(photo);
}
}
}
//Get real path form Uri
public String getRealPathFromURI(Uri contentUri) {
try {
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);
} catch (Exception e) {
return contentUri.getPath();
}
}
My problem is that ,on some mobiles it is working fine but on some it is not. For example: If i am testing my application using on my phone Yu Yureka having Lollipop ,it is giving me data as null.Also when the orientation changes,application is crashing .Please help me to fix the issue.
In your Manifest file use these permission
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Implement from this Simple Code Example this is my working example code
public void CameraClick(View v) {
Intent intent= new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// creating Dir to save clicked Photo
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/cam_Intent");
myDir.mkdirs();
// save clicked pic to given dir with given name
File file = new File(Environment.getExternalStorageDirectory(),
"/cam_Intent/MyPhoto.jpg");
outPutfileUri = Uri.fromFile(file);
intent.putExtra(MediaStore.EXTRA_OUTPUT, outPutfileUri);
startActivityForResult(intent, TAKE_PIC);
}
Bitmap bitmap = null;
#Override
protected void onActivityResult(int requestCode, int resultCode,Intent data)
{
if (requestCode == TAKE_PIC && resultCode==RESULT_OK) {
String uri = outPutfileUri.toString();
Log.e("uri-:", uri);
Toast.makeText(this, outPutfileUri.toString(),Toast.LENGTH_LONG).show();
//Bitmap myBitmap = BitmapFactory.decodeFile(uri);
// mImageView.setImageURI(Uri.parse(uri)); OR drawable make image strechable so try bleow also
try {
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), outPutfileUri);
Drawable d = new BitmapDrawable(getResources(), bitmap);
mImageView.setImageDrawable(d);
} catch (IOException e) {
e.printStackTrace();
}
}
}

Out of Memory error while loading images. [Android]

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

Android onclick radio button camera intent not working

i have a radio button. when i click on radio button camera intent is opened after taking a image using camera. image is not updating to image view.
i have used all permissions in my manifest file.
RB_PhotoStatus
.setOnCheckedChangeListener(new android.widget.RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group,
int checkedId) {
switch (checkedId) {
case R.id.yes:
//photoCollected = "Yes";
// create intent with ACTION_IMAGE_CAPTURE action
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, 0);
break;
case R.id.no:
photoCollected = "No";
break;
}
}
});
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Bitmap bp = (Bitmap) data.getExtras().get("data");
imageView1.setImageBitmap(bp);
}
Taking Photos Simply!
This answer explains how to capture photos using an existing camera application.
<manifest ... >
<uses-feature android:name="android.hardware.camera"
android:required="true" />
...
</manifest>
Request for camera application.
static final int REQUEST_IMAGE_CAPTURE = 1;
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
Camera return intent with data on Activity override function onActivityResult as bellow:-
#Override
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");
mImageView.setImageBitmap(imageBitmap);
}
}
For more info follows this link given bellow:
http://developer.android.com/training/camera/photobasics.html
It doesn't work because Camera Intent won't return the entire BitMap, but only the reference (Uri) to the created file.
Uri selectedImage = data.getData();
From this Uri you may re-load the BitMap using BitmapFactory.decodeFile
On radiobuttonclick();
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
onActivityResult();
Uri originalUri = data.getData();
imageview.setImageURI(originalUri);
And If you want to get bitmap then
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), originalUri);
private String mCurrentPhotoPath;
final String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
final File image = create_directory();
// Save a file: path for use with ACTION_VIEW intents
try {
mCurrentPhotoPath = image.getAbsolutePath();
} catch (Exception e) {
e.printStackTrace();
}
final Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
if (image != null) {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(image));
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
} else {
snackbar = Snackbar.make(findViewById(android.R.id.content), "An error has occurred", Snackbar.LENGTH_SHORT);
snackbar.setAction("Dismiss", clickListener);
snackbar.show();
}
}
}
public File create_directory() {
// Create an image file name
final String imageFileName;
final String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.ENGLISH).format(new Date());
final String user_id = "1_";
imageFileName = user_id + timeStamp + "_";
final String proj_name = "test";
final String folder_timeStamp = new SimpleDateFormat("yyyyMMdd", Locale.ENGLISH).format(new Date());
final String path = "/TEST/" + proj_name + "/" + folder_timeStamp;
final File dr = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), path);
if (!dr.exists()) {
dr.mkdirs();
}
File image = null;
try {
image = File.createTempFile(imageFileName, ".jpg", dr);
} catch (IOException e) {
e.printStackTrace();
}
return image;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE) {
if (resultCode == RESULT_OK){
//do something with the image which is stored in mCurrentPhotoPath
}
}
}

How can i catch picture that was taken?

I new in the android developing.
I want to develop simple application that will be able to take a picture using the cell phone camara and show it on the screen of the cell phone.
Is there some simple example that i can use ? or some code that can help me learn how to do it ?
Thanks for any help
to start camera you use
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, 0);
and here you have the handeling
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 0) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo);
}
}
Try this.. Use the below code in onCreate
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
URI mUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(),
"pic_" + String.valueOf(System.currentTimeMillis()) + ".jpg"));
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, mUri);
try {
intent.putExtra("return-data", true);
startActivityForResult(intent, CAMERA_RESULT);
} catch (ActivityNotFoundException e) {
e.printStackTrace();
}
Then OnActivityResult
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
//Here you will get path of image stored in sdcard then pass it to next activity as your desires..
mImagePath = extras.getString("image-path");
mSaveUri = getImageUri(mImagePath);
Bitmap mBitmap = getBitmap(mImagePath);
// here mBitmap is assigned to any imageview and you can use it in for display
}
}
private Uri getImageUri(String path) {
return Uri.fromFile(new File(path));
}
private Bitmap getBitmap(String path) {
Uri uri = getImageUri(path);
InputStream in = null;
try {
in = mContentResolver.openInputStream(uri);
return BitmapFactory.decodeStream(in).copy(Config.ARGB_8888, true);
} catch (FileNotFoundException e) {
//Log.e(TAG, "file " + path + " not found");
}
return null;
}
}

Categories

Resources