Cropping captured image is blur in android - android

Hi basically I am selecting image form gallery or capture from camera and cropping it. If I crop image which is selected from gallery is no blur its fine but if I crop captured images means its getting blur.
To start camera I have used
private void cameraIntent()
{
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAMERA);
}
and in camera onActivityResult
private void onCaptureImageResult(Intent data) {
Bitmap bm = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
crop(getImageUri(csActivity,bm));
}
This is for crop image
private void crop(Uri uri)
{
final Intent intent = new Intent("com.android.camera.action.CROP");
intent.setData(uri);
intent.putExtra("crop", "true");
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
intent.putExtra("outputX", 96);
intent.putExtra("outputY", 96);
intent.putExtra("noFaceDetection", true);
intent.putExtra("return-data", true);
startActivityForResult(intent, REQUEST_CROP);
}
and in crop result I have used
private void onCropImg(Intent data)
{
Bitmap bm = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 75, stream);
Uri tempUri = getImageUri(csActivity,bm);
// CALL THIS METHOD TO GET THE ACTUAL PATH
File destination = new File(getRealPathFromURI(tempUri));
csProfileImg.setImageBitmap(bm);
uploadProfileImg(destination);
}
and to getImageUri
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);
}
Please help me

You can use a library to crop image, that would give proper results along with the image quality. use: compile 'com.theartofdev.edmodo:android-image-cropper:2.3.+'
And for more you can visit this page: check my answer

This answer will helps others to resolve issue on capture photo from camera which gives a blur image while cropping.
By adding library in build.gradle :
implementation 'com.theartofdev.edmodo:android-image-cropper:2.3.+'
Adding Permission on Manifest :
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
CameraActivity.java :
public class CameraActivity extends Activity {
private CropImageView mCropImageView;
private CircleImageView imVCature_pic;
private Uri mCropImageUri;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera);
mCropImageView = (CropImageView) findViewById(R.id.CropImageView);
imVCature_pic = (CircleImageView) findViewById(R.id.imVCature_pic);
}
/**
* On load image button click, start pick image chooser activity.
*/
public void onLoadImageClick(View view) {
startActivityForResult(getPickImageChooserIntent(), 200);
}
/**
* Crop the image and set it back to the cropping view.
*/
public void onCropImageClick(View view) {
Bitmap cropped = mCropImageView.getCroppedImage(500, 500);
if (cropped != null)
imVCature_pic.setImageBitmap(cropped);
//mCropImageView.setImageBitmap(cropped);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
Uri imageUri = getPickImageResultUri(data);
// For API >= 23 we need to check specifically that we have permissions to read external storage,
// but we don't know if we need to for the URI so the simplest is to try open the stream and see if we get error.
boolean requirePermissions = false;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M &&
checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED &&
isUriRequiresPermissions(imageUri)) {
// request permissions and handle the result in onRequestPermissionsResult()
requirePermissions = true;
mCropImageUri = imageUri;
requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 0);
}
if (!requirePermissions) {
mCropImageView.setImageUriAsync(imageUri);
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
if (mCropImageUri != null && grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
mCropImageView.setImageUriAsync(mCropImageUri);
} else {
Toast.makeText(CameraActivity.this, "Required permissions are not granted", Toast.LENGTH_LONG).show();
}
}
/**
* Create a chooser intent to select the source to get image from.<br/>
* The source can be camera's (ACTION_IMAGE_CAPTURE) or gallery's (ACTION_GET_CONTENT).<br/>
* All possible sources are added to the intent chooser.
*/
public Intent getPickImageChooserIntent() {
// Determine Uri of camera image to save.
Uri outputFileUri = getCaptureImageOutputUri();
List<Intent> allIntents = new ArrayList<>();
PackageManager packageManager = getPackageManager();
// collect all camera intents
Intent captureIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
List<ResolveInfo> listCam = packageManager.queryIntentActivities(captureIntent, 0);
for (ResolveInfo res : listCam) {
Intent intent = new Intent(captureIntent);
intent.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
intent.setPackage(res.activityInfo.packageName);
if (outputFileUri != null) {
intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
}
allIntents.add(intent);
}
// collect all gallery intents
Intent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("image/*");
List<ResolveInfo> listGallery = packageManager.queryIntentActivities(galleryIntent, 0);
for (ResolveInfo res : listGallery) {
Intent intent = new Intent(galleryIntent);
intent.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
intent.setPackage(res.activityInfo.packageName);
allIntents.add(intent);
}
// the main intent is the last in the list (fucking android) so pickup the useless one
Intent mainIntent = allIntents.get(allIntents.size() - 1);
for (Intent intent : allIntents) {
if (intent.getComponent().getClassName().equals("com.android.documentsui.DocumentsActivity")) {
mainIntent = intent;
break;
}
}
allIntents.remove(mainIntent);
// Create a chooser from the main intent
Intent chooserIntent = Intent.createChooser(mainIntent, "Select source");
// Add all other intents
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, allIntents.toArray(new Parcelable[allIntents.size()]));
return chooserIntent;
}
/**
* Get URI to image received from capture by camera.
*/
private Uri getCaptureImageOutputUri() {
Uri outputFileUri = null;
File getImage = getExternalCacheDir();
if (getImage != null) {
outputFileUri = Uri.fromFile(new File(getImage.getPath(), "pickImageResult.jpeg"));
}
return outputFileUri;
}
/**
* Get the URI of the selected image from {#link #getPickImageChooserIntent()}.<br/>
* Will return the correct URI for camera and gallery image.
*
* #param data the returned data of the activity result
*/
public Uri getPickImageResultUri(Intent data) {
boolean isCamera = true;
if (data != null && data.getData() != null) {
String action = data.getAction();
isCamera = action != null && action.equals(MediaStore.ACTION_IMAGE_CAPTURE);
}
return isCamera ? getCaptureImageOutputUri() : data.getData();
}
/**
* Test if we can open the given Android URI to test if permission required error is thrown.<br>
*/
public boolean isUriRequiresPermissions(Uri uri) {
try {
ContentResolver resolver = getContentResolver();
InputStream stream = resolver.openInputStream(uri);
stream.close();
return false;
} catch (FileNotFoundException e) {
if (e.getCause() instanceof Exception) {
return true;
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
}
activity_camera.xml :
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="onLoadImageClick"
android:padding="#dimen/activity_horizontal_margin"
android:text="Load Image" />
<com.theartofdev.edmodo.cropper.CropImageView
android:id="#+id/CropImageView"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="5"
android:scaleType="fitCenter" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="onCropImageClick"
android:padding="#dimen/activity_horizontal_margin"
android:text="Crop Image" />
</LinearLayout>

Related

setImageBitmap not displaying

On click, my app gives choice between camera and gallery and that picture is then displayed in an ImageView. I originally tried to display the full image and then tried to use the bitmap way but nothing works. I just get a blank ImageView. Please give me some guidance as to what I'm doing wrong and ask for clarifications if necessary:
Camera/gallery photo code:
Uri outputFileUri;
private void openImageIntent() {
// Determine Uri of camera image to save.
final File root = new File(Environment.getExternalStorageDirectory() + File.separator + "MyDir" + File.separator);
root.mkdirs();
final String fname = "img_" + System.currentTimeMillis() + ".jpg";
final File sdImageMainDirectory = new File(root, fname);
outputFileUri = Uri.fromFile(sdImageMainDirectory);
// Camera.
final List<Intent> cameraIntents = new ArrayList<Intent>();
final Intent captureIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
final PackageManager packageManager = getPackageManager();
final List<ResolveInfo> listCam = packageManager.queryIntentActivities(captureIntent, 0);
for(ResolveInfo res : listCam) {
final String packageName = res.activityInfo.packageName;
final Intent intent = new Intent(captureIntent);
intent.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
intent.setPackage(packageName);
intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
cameraIntents.add(intent);
}
// Filesystem.
final Intent galleryIntent = new Intent();
galleryIntent.setType("image/*");
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
// Chooser of filesystem options.
final Intent chooserIntent = Intent.createChooser(galleryIntent, "Select Source");
// Add the camera options.
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, cameraIntents.toArray(new Parcelable[]{}));
startActivityForResult(chooserIntent, 0);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent returnIntent) {
super.onActivityResult(resultCode, requestCode, returnIntent);
if(requestCode == 0) {
if(resultCode == RESULT_OK) {
final boolean isCamera;
if(returnIntent == null) {
isCamera = true;
}
else
{
final String action = returnIntent.getAction();
if(action == null) {
isCamera = false;
}
else {
isCamera = action.equals(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
}
}
Uri selectedImageUri;
if(isCamera) {
selectedImageUri = outputFileUri;
mainImage.setImageURI(selectedImageUri); //trying full image
}
else {
selectedImageUri = returnIntent == null ? null : returnIntent.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedImageUri);
mainImage.setImageBitmap(bitmap); //trying bitmap
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
your code is 2000000000000000% ok i test it myself
Your problem is your ImageView can't show image because of image size. I try this code with ImageView like this
<ImageView
android:id="#+id/mainImage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:src="#drawable/abc_ab_bottom_solid_dark_holo" />
If you use height and width with dp like this
android:layout_width="100dp"
android:layout_height="100dp"
You need to compress the Bitmap to show it in ImageView.
Edit your code to conversion
if(isCamera) {
selectedImageUri = outputFileUri;
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedImageUri);//You can use this bitmap if need full image to further use
Bitmap bitmap2 = Bitmap.createScaledBitmap(bitmap, 600 ,600, true);//this bitmap2 you can use only for display
mainImage.setImageBitmap(bitmap2); //trying full image
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else {
selectedImageUri = returnIntent == null ? null : returnIntent.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedImageUri);
bitmap = Bitmap.createScaledBitmap(bitmap, 600 ,600, true);
mainImage.setImageBitmap(bitmap); //trying bitmap
} catch (IOException e) {
e.printStackTrace();
}
}
If you want to take image from camera you can go with this process:
public void fromCamera(){
String path= Environment.getExternalStorageDirectory().getPath() + "/DCIM/Camera/";
File file = new File(path,"IMG_"+System.currentTimeMillis()+".jpg");
file.getParentFile().mkdirs();
try {
file.createNewFile();
}catch (IOException e) {
e.printStackTrace();
}
mPicCaptureUri = Uri.fromFile(file);
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, mPicCaptureUri);
startActivityForResult(intent, REQUEST_CAMERA);
}
And if you want image from gallery then :
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(Intent.createChooser(intent, getString(R.string.select_file)), REQUEST_GALLERY);
On your onActivityResult you can get the image path of selected one and set image in image view....
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK){
if (requestCode == REQUEST_GALLERY && data != null && data.getData() != null) {
Uri selectedImageUri = data.getData();
//do set your image here
}else if(requestCode == REQUEST_CAMERA){
if(mPicCaptureUri!=null){
//do try to set image here
}
}
}
}
don't forgrt to define mPicCaptureUri at the top as:
private Uri mPicCaptureUri = null;
You can take idea from above code ..it might help you
Now you could use Picasso Library :D
Picasso.with(context)
.load(item.getPhotoUri())
.resize(512,512)
.placeholder(R.drawable.noimage)
.error(R.drawable.error_image)
.into(photo);
This mostly happens due to image being too big to be rendered by bitmap within that span of nano second during runtime, so you won't see it. Use a library called Glide. It solved all my image issues in Android including performance when there are hundreds of images to be displayed in a single list or grid.

Always Null returned after cropping a photo from a Uri in Android Lollipop?

I tried to crop an image from a Uri after taking a photo or picking a picture. And my codes are like these:
public static void cropImage(Uri uri, Activity activity, int action_code) {
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setDataAndType(uri, "image/*");
intent.putExtra("crop", "true");
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
intent.putExtra("outputX", 600);
intent.putExtra("outputY", 600);
intent.putExtra("scale", true);
intent.putExtra("return-data", true);
if (intent.resolveActivity(activity.getPackageManager()) != null) {
activity.startActivityForResult(intent, action_code);
} else {
Toast.makeText(activity, "No Crop App Available", Toast.LENGTH_SHORT).show();
}
}
And overridding onActivityResult() like this:
if (resultCode == Activity.RESULT_OK && requestCode == Utils.CODE_CROP_IMAGE) {
Bundle extras = data.getExtras();
showCenterToast("ccc");
if (extras != null) {
showCenterToast("CCC");
Bitmap photo = extras.getParcelable("data");
ivAvatar.setImageBitmap(photo); // display image in ImageView
FileOutputStream fos = null;
try {
fos = new FileOutputStream(Utils.AVATAR_FILE);
photo.compress(Bitmap.CompressFormat.PNG, 100, fos);// (0-100)compressing file
showCenterToast("DDD");
Utils.AVATAR_FILE_TMP.delete();
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
IoUtil.closeSilently(fos);
}
}
}
On devices in Android Pre-Lollipop, I was able to obtain Bitmap photo and display it in an ImageView. But, on Android Lollipop, I always got null from data.getExtras();.
I googled a lot but got few useful things about cropping an image on Android Lollipop.
Android changed its returning mechanism of cropping of com.android.camera.action.CROP on Lollipop. So, what is the new mechanism? How could I get the returned Bitmap after cropping on Lollipop?
Any tips will be appreciated. Thanks in advance.
I think that your problem has nothing to do with Android version but the image you want to be cropped. Cropping image processed in class com.android.gallery3d.filtershow.crop.CropActivity#BitmapIOTask. When the image is too large to return, it will try to return the thumb of the image, and will return null sometimes.
To avoid this, you can get the uri of cropped image instead of bitmap by setting intent.putExtra(MediaStore.EXTRA_OUTPUT, tmpUri); where tmpUri is an uri created to hold the result. And then you can get the bitmap from tmpUri.
Sample code:
private static final String IMAGE_FILE_LOCATION = "file:///sdcard/temp.jpg";//temp file
private static Uri tmpUri = Uri.parse(IMAGE_FILE_LOCATION);//The Uri to store the big bitmap
public static void cropImage(Uri uri, Activity activity, int action_code) {
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setDataAndType(uri, "image/*");
intent.putExtra("crop", "true");
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
intent.putExtra("outputX", 600);
intent.putExtra("outputY", 600);
intent.putExtra("scale", true);
intent.putExtra(MediaStore.EXTRA_OUTPUT, tmpUri);
if (intent.resolveActivity(activity.getPackageManager()) != null) {
activity.startActivityForResult(intent, action_code);
} else {
Toast.makeText(activity, "No Crop App Available", Toast.LENGTH_SHORT).show();
}
}
And in function onActivityResult:
if (resultCode == Activity.RESULT_OK && requestCode == Utils.CODE_CROP_IMAGE) {
// Bundle extras = data.getExtras();
Uri uri = data.getData();
showCenterToast("ccc");
if (uri != null) {
showCenterToast("CCC");
// Bitmap photo = null;
// if (tmpUri != null) {
// photo = decodeBitmapFromUri(tmpUri); // Get bitmap from uri.
// }
Bitmap photo = decodeUriAsBitmap(uri);
ivAvatar.setImageBitmap(photo); // display image in ImageView
FileOutputStream fos = null;
try {
fos = new FileOutputStream(Utils.AVATAR_FILE);
photo.compress(Bitmap.CompressFormat.PNG, 100, fos);// (0-100)compressing file
showCenterToast("DDD");
Utils.AVATAR_FILE_TMP.delete();
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
IoUtil.closeSilently(fos);
}
} else {
showCenterToast("Uri is NULL");
}
}
private Bitmap decodeUriAsBitmap(Uri uri){
Bitmap bitmap = null;
try {
bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri));
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
}
return bitmap;
}
I have not test whether my code was correct, but I think you can fix the bugs.
I Solved It and Working Now
Basically when cropping image in fragment the issue is here, when you use activity you should pass intent in this way in on activity result for best approach to cropping follow this library
compile 'com.theartofdev.edmodo:android-image-cropper:2.5.+'.
CropImage.activity(imageUri)
.setGuidelines(CropImageView.Guidelines.ON)
.start(getActivity());
When you use Fragment you should use:
Uri selectedImageUri = data.getData();
CropImage.activity(selectedImageUri)
.setGuidelines(CropImageView.Guidelines.ON)
.start(getContext(), this);
Sometimes getcontext requires api 23 this is because you using app.fragment, so use android.support.v4.app.
Cropping Image with activity and Fragment is Different, see here i have Successfully Implement this thing.follow the link here, for guideline.
how cropping image with in activity and fragment !!!
I was feeling difficulty while cropping image in fragment so its not solved. First you take image from camera or gallery.
private void openGallery() {
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, REQUEST_CODE_GALLERY);
}
In case of taking image from camera don't forget to include file provider Manifest fil , if you fee trouble then before doing next follow this link.
Android - file provider - permission denial
private String mCurrentPhotoPath;
private void openCameranoughat() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getActivity().getPackageManager()) != null) {
Uri photoURI = null;
try {
File photoFile = createImageFile();
path = photoFile.getAbsolutePath();
photoURI = FileProvider.getUriForFile(getActivity(),
BuildConfig.APPLICATION_ID + ".provider",
createImageFile());
} catch (IOException ex) {
Log.e("TakePicture", ex.getMessage());
}
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.LOLLIPOP) {
takePictureIntent.setClipData(ClipData.newRawUri("", photoURI));
takePictureIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
}
startActivityForResult(takePictureIntent, REQUEST_CODE_CAPTURE);
}
}
private File createImageFile() throws IOException {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.ENGLISH).format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File path = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
File file = new File(path, "DemoPicture.jpg");
try {
// Make sure the Pictures directory exists.
path.mkdirs();
} catch (Exception e) {
}
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = "file:" + file.getAbsolutePath();
return file;
}
Now on activity result for Fragment Activity you have to write this code.
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK) {
return;
}
switch (requestCode) {
case ACTION_REQUEST_EDITIMAGE://
handleEditorImage(data);
break;
case REQUEST_CODE_GALLERY:
if (mCurrentPhotoPath == null) {
Uri selectedImageUri = data.getData();
CropImage.activity(selectedImageUri)
.setGuidelines(CropImageView.Guidelines.ON)
.start(getContext(), this);
}
break;
case REQUEST_CODE_CAPTURE:
try {
Uri imageUri = Uri.parse(mCurrentPhotoPath);
if (imageUri == null) {
} else {
CropImage.activity(imageUri)
.setGuidelines(CropImageView.Guidelines.ON)
.start(getContext(), this);
MediaScannerConnection.scanFile(getActivity(),
new String[]{imageUri.getPath()}, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
}
});
mCurrentPhotoPath = null;
}
} catch (Exception e) {
}
break;
case CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE:
CropImage.ActivityResult result = CropImage.getActivityResult(data);
Uri resultUri = result.getUri();
if (resultUri != null) {
path = resultUri.getPath();
if (TextUtils.isEmpty(path)) {
return;
}
Intent it = new Intent(getActivity(), EditImageActivity.class);
it.putExtra(EditImageActivity.FILE_PATH, path);
File outputFile = FileUtils.getEmptyFile("tietu"
+ System.currentTimeMillis() + ".jpg");
it.putExtra(EditImageActivity.EXTRA_OUTPUT,
outputFile.getAbsolutePath());
startActivityForResult(it,
ACTION_REQUEST_EDITIMAGE);
}
break;
case CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE:
Toast.makeText(getActivity(), "error in cropping", Toast.LENGTH_SHORT).show();
break;
}
super.onActivityResult(requestCode, resultCode, data);
}
Use intent to get image:
Intent pickImageIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
pickImageIntent.setType("image/*");
startActivityForResult(pickImageIntent, 100);
Use Activity Result to receiver data and get Uri.
Use android-crop to crop and get image.
On Lollipop, the cropped image is returned as a String reference to a uri in the result data action. Example:
final String action = data.getAction();
Uri imageUri = Uri.parse(action)

Can't set image to ImageView returned by camera

I want to set the image returned from camera to the CropImageView.
The library used is this.
The image returned by gallery is properly being set.
But with the image returned by camera, when set with setImageUri(), the ImageView is empty although it shows the image's Uri in the Log.
This is shown by Log in onActivityResult
file:///storage/emulated/0/Android/data/com.android.example/cache/pickImageResult.jpeg
When trying to set with setImageBitmap(), Bitmap photo = (Bitmap) data.getExtras().get("data") results in NullPointerException.
The code is
public class ImagePickerActivity extends AppCompatActivity {
private CropImageView mCropImageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image_picker);
Log.d("image picker", "activity created");
mCropImageView = (CropImageView) findViewById(R.id.cropImageView);
}
/**
* On load image button click, start pick image chooser activity.
*/
public void onLoadImageClick(View view) {
startActivityForResult(getPickImageChooserIntent(), 200);
}
/**
* Crop the image and set it back to the cropping view.
*/
public void onCropImageClick(View view) {
Bitmap cropped = mCropImageView.getCroppedImage(500, 500);
if (cropped != null)
mCropImageView.setImageBitmap(cropped);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
Uri imageUri = getPickImageResultUri(data);
Log.d("image picker", imageUri.toString());
/*Bitmap photo = (Bitmap) data.getExtras().get("data");
mCropImageView.setImageBitmap(photo );*/
mCropImageView.setImageUri(imageUri);
}
}
/**
* Create a chooser intent to select the source to get image from.<br/>
* The source can be camera's (ACTION_IMAGE_CAPTURE) or gallery's (ACTION_GET_CONTENT).<br/>
* All possible sources are added to the intent chooser.
*/
public Intent getPickImageChooserIntent() {
// Determine Uri of camera image to save.
Uri outputFileUri = getCaptureImageOutputUri();
List<Intent> allIntents = new ArrayList<>();
PackageManager packageManager = getPackageManager();
// collect all camera intents
Intent captureIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
List<ResolveInfo> listCam = packageManager.queryIntentActivities(captureIntent, 0);
for (ResolveInfo res : listCam) {
Intent intent = new Intent(captureIntent);
intent.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
intent.setPackage(res.activityInfo.packageName);
if (outputFileUri != null) {
intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
}
allIntents.add(intent);
}
// collect all gallery intents
Intent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("image/*");
List<ResolveInfo> listGallery = packageManager.queryIntentActivities(galleryIntent, 0);
for (ResolveInfo res : listGallery) {
Intent intent = new Intent(galleryIntent);
intent.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
intent.setPackage(res.activityInfo.packageName);
allIntents.add(intent);
}
// the main intent is the last in the list so pickup the useless one
Intent mainIntent = allIntents.get(allIntents.size() - 1);
for (Intent intent : allIntents) {
if (intent.getComponent().getClassName().equals("com.android.documentsui.DocumentsActivity")) {
mainIntent = intent;
break;
}
}
allIntents.remove(mainIntent);
// Create a chooser from the main intent
Intent chooserIntent = Intent.createChooser(mainIntent, "Select source");
// Add all other intents
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, allIntents.toArray(new Parcelable[allIntents.size()]));
return chooserIntent;
}
/**
* Get URI to image received from capture by camera.
*/
private Uri getCaptureImageOutputUri() {
Uri outputFileUri = null;
File getImage = getExternalCacheDir();
if (getImage != null) {
outputFileUri = Uri.fromFile(new File(getImage.getPath(), "pickImageResult.jpeg"));
}
return outputFileUri;
}
/**
* Get the URI of the selected image from {#link #getPickImageChooserIntent()}.<br/>
* Will return the correct URI for camera and gallery image.
*
* #param data the returned data of the activity result
*/
public Uri getPickImageResultUri(Intent data) {
boolean isCamera = true;
if (data != null) {
String action = data.getAction();
isCamera = action != null && action.equals(MediaStore.ACTION_IMAGE_CAPTURE);
}
return isCamera ? getCaptureImageOutputUri() : data.getData();
}
}
Please help to fix this issue. Thanks in advance.
The code is taken from here.
For getting image from camera I am using below code, its working in lollipop also:
private void captureFromCamera()
Calendar calendar = Calendar.getInstance();
String fileName = String.valueOf(calendar.getTimeInMillis());
fileName += ".jpg";
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, fileName);
values.put(MediaStore.Images.Media.DESCRIPTION,
"Image capture by camera");
Uri imageUri = activity.getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
new DevicePreferences().addKey(activity, Constants.IMAGE_URI,
imageUri.toString()); // Storing in shared preference and in onActivityResult getting uri from shared preference
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
startActivityForResult(intent,
CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
}
Can u replace this code
Uri imageUri = getPickImageResultUri(data);
Log.d("image picker", imageUri.toString());
mCropImageView.setImageUri(imageUri);
with.. This,
Uri imageUri = data.getData();
path = GetPathFromURI(context, imageUri);
bitmap = BitmapFactory.decodeFile(path);
mCropImageView.setImageBitmap(bitmap);
GetPathFromURI
public static String GetPathFromURI(Context context,Uri contentUri) {
String realPath = "";
String[] projection = { MediaStore.Images.Media.DATA };
ContentResolver cr = context.getContentResolver();
Cursor cursor = cr.query(contentUri, projection, null, null, null);
if (cursor.moveToFirst()) {
realPath = cursor.getString(0);
}
cursor.close();
return realPath;
}

crop issue in android : Image aspect ratio is not maintained [duplicate]

I am having a hard time in figuring out how to let the user crop the picture.
I would like to give bitmap variable with loaded bitmap to crop the picture before setting it as wallpaper. But I'm failing to do so... Here is that i tried.
First version. = Works as expected BUT the returned image is in poor resolution. Changing the output to higher value doesn't help. As I saw in some post it is not recommended to use camera as not all devices support this.
Intent intent = new Intent("com.android.camera.action.CROP");
String path = Images.Media.insertImage(context.getContentResolver(), loaded,null, null);
Uri uri = Uri.parse(path);
intent.setData(uri);
intent.putExtra("crop", "true");
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
intent.putExtra("outputX", 300);
intent.putExtra("outputY", 300);
intent.putExtra("noFaceDetection", true);
intent.putExtra("return-data", true);
startActivityForResult(intent, 2);
Second. Load up image chooser, and crop afterwards. How can I configurate this to load crop directly on my image? Just like in version 1
Intent photoPickerIntent = new Intent(MediaStore.ACTION_PICK);
photoPickerIntent.setData(uri);
photoPickerIntent.putExtra("crop", "true");
photoPickerIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
photoPickerIntent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
startActivityForResult(photoPickerIntent, 2);
And onActivity result
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK) { return; }
if(requestCode == 2) {
Bundle extras = data.getExtras();
if(extras != null ) {
Bitmap photo = extras.getParcelable("data");
loaded = photo;
}
WallpaperManager myWallpaperManager = WallpaperManager.getInstance(getApplicationContext());
try {
myWallpaperManager.setBitmap(loaded);
} catch (IOException e) {}
}
}
I do not know whever these are the correct methods to make this done, but I hope somebody could point me in the right direction. Which, why, and how to use.
Update: I am still waiting for someone to point out how to do it correctly, answers below are working but returning images in poor resolution, so they are not an option to use
Ok Dear Here I put my Whole code of Crop Image In Android.
This the Global variable.
//This For Image Crop
/**
* Uri for set image crop option .
*/
private Uri mImageCaptureUri;
/**
* int for set key and get key from result activity .
*/
public final int CROP_FROM_CAMERA = 0;
/**
* Bitmap for apply Crop Operation Result.
*/
private Bitmap _tempOpration;
//This is Crop Method.
/**
* Method for apply Crop .
* #param filePath - String path of file .
*/
private void doCrop(String filePath){
try{
//New Flow
mImageCaptureUri = Uri.fromFile(new File(filePath));
final ArrayList<CropOption> cropOptions = new ArrayList<CropOption>();
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setType("image/*");
List<ResolveInfo> list = getPackageManager().queryIntentActivities( intent, 0 );
int size = list.size();
if (size == 0)
{
Toast.makeText(this, "Can not find image crop app", Toast.LENGTH_SHORT).show();
return;
}
else
{
intent.setData(mImageCaptureUri);
intent.putExtra("outputX", 300);
intent.putExtra("outputY", 300);
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
intent.putExtra("scale", true);
intent.putExtra("return-data", true);
if (size == 1)
{
Intent i = new Intent(intent);
ResolveInfo res = list.get(0);
i.setComponent( new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
startActivityForResult(i, CROP_FROM_CAMERA);
}
else
{
for (ResolveInfo res : list)
{
final CropOption co = new CropOption();
co.title = getPackageManager().getApplicationLabel(res.activityInfo.applicationInfo);
co.icon = getPackageManager().getApplicationIcon(res.activityInfo.applicationInfo);
co.appIntent= new Intent(intent);
co.appIntent.setComponent( new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
cropOptions.add(co);
}
CropOptionAdapter adapter = new CropOptionAdapter(getApplicationContext(), cropOptions);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Choose Crop App");
builder.setAdapter( adapter, new DialogInterface.OnClickListener()
{
public void onClick( DialogInterface dialog, int item )
{
startActivityForResult( cropOptions.get(item).appIntent, CROP_FROM_CAMERA);
}
});
builder.setOnCancelListener( new DialogInterface.OnCancelListener()
{
public void onCancel( DialogInterface dialog )
{
if (mImageCaptureUri != null )
{
getContentResolver().delete(mImageCaptureUri, null, null );
mImageCaptureUri = null;
}
}
} );
AlertDialog alert = builder.create();
alert.show();
}
}
}
catch (Exception ex)
{
genHelper.showErrorLog("Error in Crop Function-->"+ex.toString());
}
}
This is the another Class witch use for find Crop Activity Intent in Application.
CropOption Class.
public class CropOption
{
public CharSequence title;
public Drawable icon;
public Intent appIntent;
}
this is use For Display List.
CropOptionAdapter
public class CropOptionAdapter extends ArrayAdapter<CropOption>
{
private ArrayList<CropOption> mOptions;
private LayoutInflater mInflater;
public CropOptionAdapter(Context context, ArrayList<CropOption> options)
{
super(context, R.layout.crop_selector, options);
mOptions = options;
mInflater = LayoutInflater.from(context);
}
#Override
public View getView(int position, View convertView, ViewGroup group)
{
if (convertView == null)
convertView = mInflater.inflate(R.layout.crop_selector, null);
CropOption item = mOptions.get(position);
if (item != null) {
((ImageView) convertView.findViewById(R.id.iv_icon)).setImageDrawable(item.icon);
((TextView) convertView.findViewById(R.id.tv_name)).setText(item.title);
return convertView;
}
return null;
}
}
Layout File For CropOptionAdapter
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:gravity="center_vertical">
<ImageView
android:id="#+id/iv_icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:id="#+id/tv_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""/>
</LinearLayout>
This is the resultActivity.witch give the crop image.
/**
* #see android.app.Activity#onActivityResult(int, int, android.content.Intent)
*/
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (resultCode != RESULT_OK) return;
switch (requestCode)
{
case CROP_FROM_CAMERA:
if (data == null)
{
genHelper.showToast("No Crop Activity in This");
return;
}
final Bundle extras = data.getExtras();
if (extras != null)
{
try
{
_tempOpration=extras.getParcelable("data");
imageLayout.setImageBitmap(_tempOpration);
_tempOpration=null;
}
catch (Exception e)
{
e.printStackTrace();
}
}
break;
}
}
//Do This Type It's work on my live app.
genHelper.showToast("No Crop Activity in This");
is my general Class to help display toast message and Error Log.
Bestof Luck.
First, variables:
final int PIC_CROP = 2;
Uri imageUri;
Bitmap thePic;
Before you take a pic from your Camera or your Gallery, put your image into a Uri (imageUri) , use a method called here as "performCrop()" inside try/catch:
private void performCrop(){
try {
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setType("image/*");
List<ResolveInfo> list = getPackageManager().queryIntentActivities( intent, 0 );
int size = list.size();
if (size >= 0) {
intent.setData(imageUri);
intent.putExtra("crop", "false");
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
intent.putExtra("outputX", 256);
intent.putExtra("outputY", 256);
intent.putExtra("scale", true);
intent.putExtra("return-data", true);
Intent i = new Intent(intent);
ResolveInfo res = list.get(0);
i.setComponent( new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
startActivityForResult(i, PIC_CROP);
}
}
catch(ActivityNotFoundException anfe){
String errorMessage = "Whoops - your device doesn't support the crop action!";
Toast toast = Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT);
toast.show();
}
}
On method onActivityResult:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
if(requestCode == PIC_CROP){
if (resultCode == RESULT_OK) {
Bundle extras = intent.getExtras();
thePic = extras.getParcelable("data");
imageViewPhoto.setImageBitmap(thePic); //in my case, set the image on screen
}else{
//do something
}
}
}
As mentioned in similar threads, Android does not have an official crop intent
(https://commonsware.com/blog/2013/01/23/no-android-does-not-have-crop-intent.html), so I would stay away from using "com.android.camera.action.CROP".
However, in the time since this question was originally posted, Android has added a new API in Kitkat (level 19) that allows users to summon a crop-this-image-and-set-as-wallpaper Activity. See WallpaperManager.getCropAndSetWallpaperIntent(), and this might address your original question.
I also had the problem using the camera and ACTION_PICK that the returned image was very small despite the passed resolution being much larger. I got around this storing the resulted crop image in a temporary file
// temporary storage location, preferably in your cache directory
private final String tempFilePath = "somePath";
// URI instantiated with your temporary storage location
private Uri tempuri = Uri.fromFile(new File(tempFilePath));
// code for startActivityForResult
private final static int ACTIVITY_CROP_IMAGE = 1;
and calling the intent like this
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
photoPickerIntent.setType("image/*");
photoPickerIntent.putExtra("crop", "true");
photoPickerIntent.putExtra("aspectX", wallpaperWidth);
photoPickerIntent.putExtra("aspectY", wallpaperHeight);
photoPickerIntent.putExtra(MediaStore.EXTRA_OUTPUT, tempuri);
photoPickerIntent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
startActivityForResult(photoPickerIntent, ACTIVITY_CROP_IMAGE);
and then in onActivityResult
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (resultCode != RESULT_OK)
return;
if(requestCode == ACTIVITY_CROP_IMAGE)
{
try
{
Bitmap bmp = BitmapFactory.decodeFile(tempFilePath);
if(bmp != null)
{
WallpaperManager myWallpaperManager = WallpaperManager.getInstance(getApplicationContext());
myWallpaperManager.setBitmap(bmp);
}
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
if(tempFilePath != null)
{
File tempFile = new File(tempFilePath);
if(tempFile.exists())
{
tempFile.delete();
}
}
}
}
}
I constructed the above code from the top of my head and didn't actually compile any of it. But the basics are correct and you should get the hang ;-)

Let user crop image

I am having a hard time in figuring out how to let the user crop the picture.
I would like to give bitmap variable with loaded bitmap to crop the picture before setting it as wallpaper. But I'm failing to do so... Here is that i tried.
First version. = Works as expected BUT the returned image is in poor resolution. Changing the output to higher value doesn't help. As I saw in some post it is not recommended to use camera as not all devices support this.
Intent intent = new Intent("com.android.camera.action.CROP");
String path = Images.Media.insertImage(context.getContentResolver(), loaded,null, null);
Uri uri = Uri.parse(path);
intent.setData(uri);
intent.putExtra("crop", "true");
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
intent.putExtra("outputX", 300);
intent.putExtra("outputY", 300);
intent.putExtra("noFaceDetection", true);
intent.putExtra("return-data", true);
startActivityForResult(intent, 2);
Second. Load up image chooser, and crop afterwards. How can I configurate this to load crop directly on my image? Just like in version 1
Intent photoPickerIntent = new Intent(MediaStore.ACTION_PICK);
photoPickerIntent.setData(uri);
photoPickerIntent.putExtra("crop", "true");
photoPickerIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
photoPickerIntent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
startActivityForResult(photoPickerIntent, 2);
And onActivity result
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK) { return; }
if(requestCode == 2) {
Bundle extras = data.getExtras();
if(extras != null ) {
Bitmap photo = extras.getParcelable("data");
loaded = photo;
}
WallpaperManager myWallpaperManager = WallpaperManager.getInstance(getApplicationContext());
try {
myWallpaperManager.setBitmap(loaded);
} catch (IOException e) {}
}
}
I do not know whever these are the correct methods to make this done, but I hope somebody could point me in the right direction. Which, why, and how to use.
Update: I am still waiting for someone to point out how to do it correctly, answers below are working but returning images in poor resolution, so they are not an option to use
Ok Dear Here I put my Whole code of Crop Image In Android.
This the Global variable.
//This For Image Crop
/**
* Uri for set image crop option .
*/
private Uri mImageCaptureUri;
/**
* int for set key and get key from result activity .
*/
public final int CROP_FROM_CAMERA = 0;
/**
* Bitmap for apply Crop Operation Result.
*/
private Bitmap _tempOpration;
//This is Crop Method.
/**
* Method for apply Crop .
* #param filePath - String path of file .
*/
private void doCrop(String filePath){
try{
//New Flow
mImageCaptureUri = Uri.fromFile(new File(filePath));
final ArrayList<CropOption> cropOptions = new ArrayList<CropOption>();
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setType("image/*");
List<ResolveInfo> list = getPackageManager().queryIntentActivities( intent, 0 );
int size = list.size();
if (size == 0)
{
Toast.makeText(this, "Can not find image crop app", Toast.LENGTH_SHORT).show();
return;
}
else
{
intent.setData(mImageCaptureUri);
intent.putExtra("outputX", 300);
intent.putExtra("outputY", 300);
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
intent.putExtra("scale", true);
intent.putExtra("return-data", true);
if (size == 1)
{
Intent i = new Intent(intent);
ResolveInfo res = list.get(0);
i.setComponent( new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
startActivityForResult(i, CROP_FROM_CAMERA);
}
else
{
for (ResolveInfo res : list)
{
final CropOption co = new CropOption();
co.title = getPackageManager().getApplicationLabel(res.activityInfo.applicationInfo);
co.icon = getPackageManager().getApplicationIcon(res.activityInfo.applicationInfo);
co.appIntent= new Intent(intent);
co.appIntent.setComponent( new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
cropOptions.add(co);
}
CropOptionAdapter adapter = new CropOptionAdapter(getApplicationContext(), cropOptions);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Choose Crop App");
builder.setAdapter( adapter, new DialogInterface.OnClickListener()
{
public void onClick( DialogInterface dialog, int item )
{
startActivityForResult( cropOptions.get(item).appIntent, CROP_FROM_CAMERA);
}
});
builder.setOnCancelListener( new DialogInterface.OnCancelListener()
{
public void onCancel( DialogInterface dialog )
{
if (mImageCaptureUri != null )
{
getContentResolver().delete(mImageCaptureUri, null, null );
mImageCaptureUri = null;
}
}
} );
AlertDialog alert = builder.create();
alert.show();
}
}
}
catch (Exception ex)
{
genHelper.showErrorLog("Error in Crop Function-->"+ex.toString());
}
}
This is the another Class witch use for find Crop Activity Intent in Application.
CropOption Class.
public class CropOption
{
public CharSequence title;
public Drawable icon;
public Intent appIntent;
}
this is use For Display List.
CropOptionAdapter
public class CropOptionAdapter extends ArrayAdapter<CropOption>
{
private ArrayList<CropOption> mOptions;
private LayoutInflater mInflater;
public CropOptionAdapter(Context context, ArrayList<CropOption> options)
{
super(context, R.layout.crop_selector, options);
mOptions = options;
mInflater = LayoutInflater.from(context);
}
#Override
public View getView(int position, View convertView, ViewGroup group)
{
if (convertView == null)
convertView = mInflater.inflate(R.layout.crop_selector, null);
CropOption item = mOptions.get(position);
if (item != null) {
((ImageView) convertView.findViewById(R.id.iv_icon)).setImageDrawable(item.icon);
((TextView) convertView.findViewById(R.id.tv_name)).setText(item.title);
return convertView;
}
return null;
}
}
Layout File For CropOptionAdapter
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:gravity="center_vertical">
<ImageView
android:id="#+id/iv_icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:id="#+id/tv_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""/>
</LinearLayout>
This is the resultActivity.witch give the crop image.
/**
* #see android.app.Activity#onActivityResult(int, int, android.content.Intent)
*/
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (resultCode != RESULT_OK) return;
switch (requestCode)
{
case CROP_FROM_CAMERA:
if (data == null)
{
genHelper.showToast("No Crop Activity in This");
return;
}
final Bundle extras = data.getExtras();
if (extras != null)
{
try
{
_tempOpration=extras.getParcelable("data");
imageLayout.setImageBitmap(_tempOpration);
_tempOpration=null;
}
catch (Exception e)
{
e.printStackTrace();
}
}
break;
}
}
//Do This Type It's work on my live app.
genHelper.showToast("No Crop Activity in This");
is my general Class to help display toast message and Error Log.
Bestof Luck.
First, variables:
final int PIC_CROP = 2;
Uri imageUri;
Bitmap thePic;
Before you take a pic from your Camera or your Gallery, put your image into a Uri (imageUri) , use a method called here as "performCrop()" inside try/catch:
private void performCrop(){
try {
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setType("image/*");
List<ResolveInfo> list = getPackageManager().queryIntentActivities( intent, 0 );
int size = list.size();
if (size >= 0) {
intent.setData(imageUri);
intent.putExtra("crop", "false");
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
intent.putExtra("outputX", 256);
intent.putExtra("outputY", 256);
intent.putExtra("scale", true);
intent.putExtra("return-data", true);
Intent i = new Intent(intent);
ResolveInfo res = list.get(0);
i.setComponent( new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
startActivityForResult(i, PIC_CROP);
}
}
catch(ActivityNotFoundException anfe){
String errorMessage = "Whoops - your device doesn't support the crop action!";
Toast toast = Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT);
toast.show();
}
}
On method onActivityResult:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
if(requestCode == PIC_CROP){
if (resultCode == RESULT_OK) {
Bundle extras = intent.getExtras();
thePic = extras.getParcelable("data");
imageViewPhoto.setImageBitmap(thePic); //in my case, set the image on screen
}else{
//do something
}
}
}
As mentioned in similar threads, Android does not have an official crop intent
(https://commonsware.com/blog/2013/01/23/no-android-does-not-have-crop-intent.html), so I would stay away from using "com.android.camera.action.CROP".
However, in the time since this question was originally posted, Android has added a new API in Kitkat (level 19) that allows users to summon a crop-this-image-and-set-as-wallpaper Activity. See WallpaperManager.getCropAndSetWallpaperIntent(), and this might address your original question.
I also had the problem using the camera and ACTION_PICK that the returned image was very small despite the passed resolution being much larger. I got around this storing the resulted crop image in a temporary file
// temporary storage location, preferably in your cache directory
private final String tempFilePath = "somePath";
// URI instantiated with your temporary storage location
private Uri tempuri = Uri.fromFile(new File(tempFilePath));
// code for startActivityForResult
private final static int ACTIVITY_CROP_IMAGE = 1;
and calling the intent like this
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
photoPickerIntent.setType("image/*");
photoPickerIntent.putExtra("crop", "true");
photoPickerIntent.putExtra("aspectX", wallpaperWidth);
photoPickerIntent.putExtra("aspectY", wallpaperHeight);
photoPickerIntent.putExtra(MediaStore.EXTRA_OUTPUT, tempuri);
photoPickerIntent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
startActivityForResult(photoPickerIntent, ACTIVITY_CROP_IMAGE);
and then in onActivityResult
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (resultCode != RESULT_OK)
return;
if(requestCode == ACTIVITY_CROP_IMAGE)
{
try
{
Bitmap bmp = BitmapFactory.decodeFile(tempFilePath);
if(bmp != null)
{
WallpaperManager myWallpaperManager = WallpaperManager.getInstance(getApplicationContext());
myWallpaperManager.setBitmap(bmp);
}
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
if(tempFilePath != null)
{
File tempFile = new File(tempFilePath);
if(tempFile.exists())
{
tempFile.delete();
}
}
}
}
}
I constructed the above code from the top of my head and didn't actually compile any of it. But the basics are correct and you should get the hang ;-)

Categories

Resources