I'm following this tutorial: http://mobile.tutsplus.com/tutorials/android/capture-and-crop-an-image-with-the-device-camera/
I am trying to create a simple activity that has a "take picture" Button, and an ImageView, and simply take a picture, then open the cropping activity built into Android. I can open the camera without incident, however, upon taking the photo, the code doesn't send the photo to the cropping activity.
It seems to crash when the cropping activity is called. I'm not sure why this is occurring; I followed the example exactly (except for the beginning XML stuff which I didn't need), and I looked over the code and everything seems to make sense. I'm sure it's a minor error somewhere that is causing this. Here is my code for the activity:
package com.example.project;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
public class ImageChoose extends Activity implements OnClickListener {
//keep track of camera capture intent
final int CAMERA_CAPTURE = 1;
//captured picture uri
private Uri picUri;
final int PIC_CROP = 2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image_choose);
Button takePicture = (Button)findViewById(R.id.takePicture);
takePicture.setOnClickListener(this);
}
public void onClick(View v) {
if (v.getId() == R.id.takePicture){
try{
//use standard intent to capture an image
Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//we will handle the returned data in onActivityResult
startActivityForResult(captureIntent, CAMERA_CAPTURE);
}catch(ActivityNotFoundException anfe){
//display an error message
String errorMessage = "Your device doesn't support photos!";
Toast toast = Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT);
toast.show();
}
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data){
if (resultCode == RESULT_OK){
if (requestCode == CAMERA_CAPTURE){
picUri = data.getData();
performCrop();
}else if(requestCode == PIC_CROP){
//get the returned data
Bundle extras = data.getExtras();
//get the cropped bitmap
Bitmap thePic = extras.getParcelable("data");
//retrieve a reference to the ImageView
ImageView picView = (ImageView)findViewById(R.id.picture);
//display the returned cropped image
picView.setImageBitmap(thePic);
}
}
}
private void performCrop(){
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(picUri, "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", 256);
cropIntent.putExtra("outputY", 256);
//retrieve data on return
cropIntent.putExtra("return-data", true);
//start the activity - we handle returning in onActivityResult
startActivityForResult(cropIntent, PIC_CROP);
}catch(ActivityNotFoundException anfe){
String errorMessage = "Your device doesn't support photo cropping!";
Toast toast = Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT);
toast.show();
}
}
}
I have used this type of action.Here is my code with the following link:-Detail Description
I hope this will help you.I suggest you the following Lines where you should have your focus:-
Intent camera=new Intent();
camera.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
camera.putExtra("crop", "true");
The cropping activity is part of the stock Android camera app. It may or may not be available on your device, especially if you are using a custom/vendor camera app. If you want this to work reliably, you have to take the code for the cropper and incorporate it into your own app.
private void performCrop(){
}
Inside this method we are going to call an Intent to perform the crop, so let’s add “try” and “catch” blocks in case the user device does not support the crop operation:
try {
}
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();
}
//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(picUri, "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", 256);
cropIntent.putExtra("outputY", 256);
//retrieve data on return
cropIntent.putExtra("return-data", true);
//start the activity - we handle returning in onActivityResult
startActivityForResult(cropIntent, PIC_CROP);
//keep track of cropping intent
final int PIC_CROP = 2;
Related
I am building a wallpaper app in java. When user selects an image, a small default menu should pop up like in the provided screenshot, where user can select which app should set the wallpaper.
So far I used WallpaperManager for setting the wallpaper but that doesnt give user an option to move the image etc. This is my first android app ever so I am learning with every step I take, so sorry if this is an easy task. I also have not found SO question that solves my problem.
Can you please point me to the right direction, waht should I google, look for, or show me some code that does this? Thank you in advance.
the followin code my solve your problem
File f=new File("wallpaper_file_path");
Intent i=new Intent(Intent.ACTION_SET_WALLPAPER,Uri.fromFile(f));
startActivity(i);
I made a wallpaper app, in that, I used a zoom image library so that I can adjust the image then I take the cache of that image view are and set it as wallpaper. and I can set it for the home screen, lock screen and for both
public void SetHomeAndLockScreen()
{
bmap=((BitmapDrawable)imageview.getDrawable()).getBitmap();//get the cache from zoomable imageview
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
WallpaperManager wpm = WallpaperManager.getInstance(getApplicationContext());
try {
wpm.setBitmap(bmap, null, true, WallpaperManager.FLAG_LOCK);
wpm.setBitmap(bmap);
} catch (IOException e) {
e.printStackTrace();
}
Toast.makeText(getApplicationContext(), "Wallpaper Applied", Toast.LENGTH_SHORT).show();
}
I was understand that you need to crop image from gallery try this use phone screen width for x and screen height for y
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setClassName("com.android.camera", "com.android.camera.CropImage");
File file = new File(filePath);
Uri uri = Uri.fromFile(file);
intent.setData(uri);
intent.putExtra("crop", "true");
intent.putExtra("aspectX", 4);
intent.putExtra("aspectY", 16);
intent.putExtra("outputX", 720);
intent.putExtra("outputY", 1080);
intent.putExtra("noFaceDetection", true);
intent.putExtra("return-data", true);
startActivityForResult(intent, REQUEST_CROP_ICON);`
When the picture select Activity return will be selected to save the contents.in
onActivityResult:
Bundle extras = data.getExtras();
if(extras != null ) {
Bitmap photo = extras.getParcelable("data");
ByteArrayOutputStream stream = new ByteArrayOutputStream();
photo.compress(Bitmap.CompressFormat.JPEG, 75, stream);
// The stream to write to a file or directly using the photo
} and set the wall paper using wallpaper manager
Modern solution :)
/**
* Set as wallpaper method
*/
public void setWallpaper() {
Intent intent = new Intent(Intent.ACTION_ATTACH_DATA);
intent.addCategory(Intent.CATEGORY_DEFAULT);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); // Android 7.0+ required
Uri wallUri = getImageUri(this, wallpaperDrawableBitmap);
intent.setDataAndType(wallUri, "image/jpeg");
intent.putExtra("mimeType", "image/jpeg");
this.startActivity(Intent.createChooser(intent, "Set as:"));
}
Modern solution for static contexts :)
/**
* Set as wallpaper
*/
public static void setWallpaper(Activity activity) {
Intent intent = new Intent(Intent.ACTION_ATTACH_DATA);
intent.addCategory(Intent.CATEGORY_DEFAULT);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); // Android 7.0+ required
Uri wallUri = getImageUri(activity, wallpaperDrawableBitmapStatic);
intent.setDataAndType(wallUri, "image/jpeg");
intent.putExtra("mimeType", "image/jpeg");
activity.startActivity(Intent.createChooser(intent, "Set as:"));
}
Note that setDataAndType(...) requires the image URI.
When i press the button then the camera captures the picture, I want to perform crop on that picture after Cropping but i am unable to figure out the problem because crop function is not working properly, Please Help me to figure out the problem that is the main cause of crop function is not being preformed
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
final int CAMERA_CAPTURE = 1;
final int CROP_PIC = 2;
private Uri picUri;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button captureBtn = (Button) findViewById(R.id.capture_btn);
captureBtn.setOnClickListener((View.OnClickListener) this);
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.capture_btn) {
try {
// use standard intent to capture an image
Intent captureIntent = new Intent(
MediaStore.ACTION_IMAGE_CAPTURE);
// we will handle the returned data in onActivityResult
startActivityForResult(captureIntent, CAMERA_CAPTURE);
} catch (ActivityNotFoundException anfe) {
Toast toast = Toast.makeText(this, "This device doesn't support the crop action!",
Toast.LENGTH_SHORT);
toast.show();
}
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Toast toast4 = Toast.makeText(this, Integer.toString(RESULT_OK),
Toast.LENGTH_SHORT);
toast4.show();
if (resultCode == RESULT_OK) {
Toast toast = Toast.makeText(this, "capture ok",
Toast.LENGTH_SHORT);
toast.show();
if (requestCode == CAMERA_CAPTURE) {
// get the Uri for the captured image
picUri = data.getData();
// Toast toast1 = Toast.makeText(this, Integer.toString(requestCode),
// Toast.LENGTH_SHORT);
// toast1.show();
performCrop();
}
// user is returning from cropping the image
if (requestCode == CROP_PIC) {
Toast toast1 = Toast.makeText(this, "crop ok",
Toast.LENGTH_SHORT);
toast1.show();
// get the returned data
Bundle extras = data.getExtras();
// get the cropped bitmap
Bitmap thePic = extras.getParcelable("data");
ImageView picView = (ImageView) findViewById(R.id.picture);
picView.setImageBitmap(thePic);
}
}
}
/**
* this function does the crop operation.
*/
private void performCrop() {
////////////////// 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(picUri, "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", 256);
cropIntent.putExtra("outputY", 256);
// retrieve data on return
cropIntent.putExtra("return-data", true);
// start the activity - we handle returning in onActivityResult
startActivityForResult(cropIntent, CROP_PIC);
}
catch (ActivityNotFoundException anfe) {
Toast toast3 = Toast
.makeText(this, "This device doesn't support the crop action!", Toast.LENGTH_SHORT);
toast3.show();
}
}
}
I'm trying to capture an image from the Android Camera/ Pick an image from the gallery and then crop it before performing other operations on it. I'm having trouble with getting back the URI of the cropped image. Any help on how to get back the URI of the image once it has been cropped would be much appreciated!
The code below pertains to my onActivityResult and my function performing the crop
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == SELECT_FILE || requestCode == REQUEST_IMAGE_CAPTURE) {
if(!IS_CAMERA_USED) {
selectedImageUri = data.getData();
}
performCrop();
}
else if(requestCode == CROP_IMAGE){
selectedImageUri = data.getData();
onSelectedImageResult();
}
}
}
public void performCrop() {
// take care of exceptions
Display display = getWindowManager().getDefaultDisplay();
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(selectedImageUri, "image/*");
// set crop properties
cropIntent.putExtra("crop", "true");
// indicate aspect of desired crop
cropIntent.putExtra("aspectY", 1);
if(IS_PROFILE_PICTURE) {
cropIntent.putExtra("aspectX", 1);
}
else {
cropIntent.putExtra("aspectX", 2);
}
// indicate output X and Y
cropIntent.putExtra("outputX", display.getWidth());
cropIntent.putExtra("outputY", display.getHeight());
// 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) {
Toast toast = Toast
.makeText(this, "This device doesn't support the crop action!", Toast.LENGTH_SHORT);
toast.show();
}
}
The problem is in the line selectedImageUri = data.getData(), where data.getData() returns null after having done the crop. How do I get back the URI of the cropped image? I don't want to get data.getExtras.getParcelable("data") as that returns the thumbnail and ruins the image resolution.
Thanks in advance!
You can get the image bitmap with this code:
if (requestCode == CROP_IMAGE) {
if (data != null) {
Bundle extras = data.getExtras();
if (extras != null) {
Bitmap selectedBitmap = extras.getParcelable("data");
//imgView.setImageBitmap(selectedBitmap);
}
}
}
URI is not possible I think, because the cropped image is not saved on the storage.
Thanks for all your answers, but I found something way simpler to incorporate and use that avoids all hassles due to the `com.android.camera.action.CROP' class, and it can be found here
I think that you should save the cropped Bitmap to your storage, and then use the URI of the cropped Bitmap to performe something over it!
I know it's not a professional work but at least it should do it
I am absolutely new to Android as well as Java (only some basic knowledge). I am trying to develop a simple app as per a youtube video. In this app, I have a button which is clickable and call the method launchCamera(). The image captured by the camera has to be displayed in the ImageView.
PROBLEM: I installed the .apk file in my mobile. When I click the "Take Photo" button, my camera starts. When I capture a image from my camera and save it, that image gets displayed in the ImageView only for a second (even less then a second). How can I keep that photo in the ImageView till the user does not press the "Take Photo" button again?
UPDATE: With the same code, I just noticed something strange. Mostly the image captured while holding the phone vertically rotates itself inside the ImageView and disappears. But sometimes it stays in the ImageView vertically and doesn't get disappeared till the "Take Photo" button is pressed again (Desired case).
My Code:
package com.siddexample.buttonimage;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.provider.MediaStore;
import android.content.pm.PackageInfo;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
public class ButtonImageMainActivity extends AppCompatActivity {
static final int REQUEST_IMAGE_CAPTURE = 1;
ImageView siddImageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_button_image_main);
Button siddButton = (Button) findViewById(R.id.siddButton);
siddImageView = (ImageView) findViewById(R.id.siddImageView);
}//////-------------///////////////
public void launchCamera(View view) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//Take a picture by your intent
startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap photo = (Bitmap) extras.get("data");
siddImageView.setImageBitmap(photo);
}
}
}
Try using this tutorial here , as follows:
Taking a picture:
private void captureImage() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
// start the image capture Intent
startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
}
Receiving the picture:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// if the result is capturing Image
if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// successfully captured the image
// display it in image view
previewCapturedImage();
} else if (resultCode == RESULT_CANCELED) {
// user cancelled Image capture
Toast.makeText(getApplicationContext(),
"User cancelled image capture", Toast.LENGTH_SHORT)
.show();
} else {
// failed to capture image
Toast.makeText(getApplicationContext(),
"Sorry! Failed to capture image", Toast.LENGTH_SHORT)
.show();
}
}
}
and displaying the picture:
/*
* Display image from a path to ImageView
*/
private void previewCapturedImage() {
try {
// hide video preview
videoPreview.setVisibility(View.GONE);
imgPreview.setVisibility(View.VISIBLE);
// bimatp factory
BitmapFactory.Options options = new BitmapFactory.Options();
// downsizing image as it throws OutOfMemory Exception for larger
// images
options.inSampleSize = 8;
final Bitmap bitmap = BitmapFactory.decodeFile(fileUri.getPath(),
options);
imgPreview.setImageBitmap(bitmap);
} catch (NullPointerException e) {
e.printStackTrace();
}
}
As #stkent said, maybe the onActivityResult is called twice.
so this was working lovely till yesterday when I upgraded my phone to 5.0.0 and tested the application out in a 5.0.0 emulator. Basically the purpose is to allow the user to take a photo, return it, open it to allow cropping then return it and set it as an imageview.
Everything worked fine before but now the intent in onActivityResult is null.
Here's code:
public void takeDisplayPicture(View view) {
final String TAKE_DISPLAY_PICTURE = "Take Display Picture";
Log.d(TAKE_DISPLAY_PICTURE, "Clicked");
try {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAMERA_CAPTURE);
} catch (ActivityNotFoundException e) {
String msg = "Your device doesn't support a camera!";
Toast toast = Toast.makeText(this, msg, Toast.LENGTH_SHORT);
toast.show();
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
final String RETURN_DISPLAY_PICTURE = "Return Display Picture";
Log.d(RETURN_DISPLAY_PICTURE, "Returned");
if (resultCode == RESULT_OK && requestCode == CAMERA_CAPTURE) {
picUri = data.getData();
performCrop(picUri);
} else if (requestCode == PIC_CROP) {
Bundle extras = data.getExtras();
bitmap = extras.getParcelable("data");
displayPicture.setImageBitmap(bitmap);
}
}
private void performCrop(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", 256);
cropIntent.putExtra("outputY", 256);
cropIntent.putExtra("return-data", true);
startActivityForResult(cropIntent, PIC_CROP);
} catch (ActivityNotFoundException e) {
String msg = "Your device doesn't support the crop action!";
Toast toast = Toast.makeText(this, msg, Toast.LENGTH_SHORT);
toast.show();
}
}
First, Android does not have a CROP Intent.
With respect to the null Uri, it is supposed to be null. Quoting the ACTION_IMAGE_CAPTURE documentation:
The caller may pass an extra EXTRA_OUTPUT to control where this image will be written. If the EXTRA_OUTPUT is not present, then a small sized image is returned as a Bitmap object in the extra field.
You do not have EXTRA_OUTPUT, and so you are supposed to get your image via the poorly-documented (Bitmap)data.getExtras().get("data");.