In my app i'm trying to crop images. I find some code that can crop images when a'm taking photo from camera, but i can't crop photos from gallery, cause:
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=2, result=0, data=null} to activity {....MainActivity}: java.lang.NullPointerException "
in this line: Bundle extras = data.getExtras();
This is myActivity's code:
public class MainActivity extends Activity {
ImageView imVCature_pic;
Button btnCapture;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initializeControls();
}
private void initializeControls() {
imVCature_pic=(ImageView)findViewById(R.id.imVCature_pic);
btnCapture=(Button)findViewById(R.id.btnCapture);
Button buttonGallery = (Button) findViewById(R.id.btn_select_gallery);
btnCapture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
/*create instance of File with name img.jpg*/
File file = new File(Environment.getExternalStorageDirectory() + File.separator + "img.jpg");
/*put uri as extra in intent object*/
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
/*start activity for result pass intent as argument and request code */
startActivityForResult(intent, 1);
}
});
buttonGallery.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent2 = new Intent();
intent2.setType("image/*");
intent2.setAction(Intent.ACTION_GET_CONTENT);
File file2 = new File(Environment.getExternalStorageDirectory() + File.separator + "img2.jpg");
/*put uri as extra in intent object*/
intent2.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file2));
/*start activity for result pass intent as argument and request code */
startActivityForResult(intent2, 3);
}} );
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//if request code is same we pass as argument in startActivityForResult
if(requestCode==1){
//create instance of File with same name we created before to get image from storage
File file = new File(Environment.getExternalStorageDirectory()+File.separator + "img.jpg");
//Crop the captured image using an other intent
try {
/*the user's device may not support cropping*/
cropCapturedImage(Uri.fromFile(file));
}
catch(ActivityNotFoundException aNFE){
//display an error message if user device doesn't support
String errorMessage = "Sorry - your device doesn't support the crop action!";
Toast toast = Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT);
toast.show();
}
}
if(requestCode==2){
//Create an instance of bundle and get the returned data
Bundle extras = data.getExtras();
//get the cropped bitmap from extras
Bitmap thePic = extras.getParcelable("data");
//set image bitmap to image view
imVCature_pic.setImageBitmap(thePic);
}
if(requestCode==3){
//create instance of File with same name we created before to get image from storage
File file = new File(Environment.getExternalStorageDirectory()+File.separator + "img.jpg");
//Crop the captured image using an other intent
try {
/*the user's device may not support cropping*/
cropCapturedImage(Uri.fromFile(file));
}
catch(ActivityNotFoundException aNFE){
//display an error message if user device doesn't support
String errorMessage = "Sorry - your device doesn't support the crop action!";
Toast toast = Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT);
toast.show();
}
}
}
//create helping method cropCapturedImage(Uri picUri)
public void cropCapturedImage(Uri picUri){
//call the standard crop action intent
Intent cropIntent = new Intent("com.android.camera.action.CROP");
//indicate image type and Uri of image
cropIntent.setDataAndType(picUri, "image/*");
//set crop properties
cropIntent.putExtra("crop", "true");
//indicate aspect of desired crop
cropIntent.putExtra("aspectX", 256);
cropIntent.putExtra("aspectY", 256);
//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, 2);
}
Where's a mistake?
Related
What I am trying to achieve is on the map long press it brings up and custom dialog view with 3 buttons, one for photo, one for save and one for cancel.
So at the moment when tapping on photo the camera intent opens and I can take a photo. Upon clicking "ok" the intent returns to the custom dialog window but no image is displayed?
This is my code I am using at the moment:
public void onMapLongClick(LatLng point) {
LayoutInflater factory = LayoutInflater.from(MainActivity.this);
final View deleteDialogView = factory.inflate(R.layout.custom_dialog, null);
final AlertDialog deleteDialog = new AlertDialog.Builder(MainActivity.this).create();
deleteDialog.setView(deleteDialogView);
deleteDialogView.findViewById(R.id.btn_photo).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
String f = System.currentTimeMillis()+".jpg"; // Designated name
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM), f);
fileUri = FileProvider.getUriForFile(MainActivity.this, getPackageName() + ".fileprovider", file);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(cameraIntent, TAKE_PICTURE);
}
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
switch (requestCode) {
case TAKE_PICTURE:
ImageView imgView = findViewById(R.id.a);
imgView.setImageURI(fileUri);
break;
}
}
});
Notice that you pass 'fileUri' to the intent, so you also need to get it from the returned intent.
Try replacing imgView.setImageURI(fileUri);
with imgView.setImageURI(data.getData());
or
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
which will give you the URI with the image.
I am having an Application which captures an image and send the ImageUri to Crop Intent for cropping. Some of the photos are getting cropped properly. When there is a change in resolution Application(i.e. Photo taken using front camera with different resolution or Uploading a downloaded images) is getting terminated automatically without any error.
Code to open Camera
fabcamera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Open Camera and upload the photo
Intent cameraIntent=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent,CAMERA_CAPTURE);
}
});
private void performCrop(Uri picUri){
Intent cropIntent = new Intent("com.android.camera.action.CROP");
cropIntent.setDataAndType(picUri, "image/*");
cropIntent.putExtra("crop", "true");
cropIntent.putExtra("aspectX", 0);
cropIntent.putExtra("aspectY", 0);
cropIntent.putExtra("outputX", 0);
cropIntent.putExtra("outputY", 0);
cropIntent.putExtra("return-data", true);
startActivityForResult(cropIntent, PIC_CROP);
}
fabgallery.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Open Gallery and upload the photo
Intent intent=new Intent(Intent.ACTION_PICK,MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/*");
startActivityForResult(intent.createChooser(intent,"Select File"),SELECT_FILE);
}
});
Can anyone give me a suggestion?
I am trying to read image from gallery and then use that image for input straming , below is my code
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mGetImageButton = (Button) findViewById(R.id.button_getImage);
mGetImageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// SET action AND miniType
Intent intent = new Intent();
intent.setAction(Intent.ACTION_PICK);
intent.setType("image/*");
// REQUEST Uri of image
startActivityForResult(intent, REQUEST_IMAGE);
}
});
mImageViewForGallery = (ImageView) findViewById(R.id.imageView2);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode != Activity.RESULT_OK) {return;}
if (requestCode == REQUEST_IMAGE) {
Uri uri = data.getData();
// SET image
mImageViewForGallery.setImageURI(uri);
Drawable drawable = mImageViewForGallery.getDrawable();
InputStream is;
is = this.getResources().openRawResource(R.drawable.img1);
Bitmap bmInImg = BitmapFactory.decodeStream(is);
}
}
In above code is = this.getResources().openRawResource(R.drawable.img1); is reading image from drawable folder name img1 , but now my image is the image I select from gallery , How I can take that image as input stream, as I tried it like
InputStream is;
is=uri;
But its showing error , well am new to java from c++.
Edit, after #Shawn answer I put this code in onActivityResult function after line Drawable drawable = mImageViewForGallery.getDrawable(); :
InputStream is = this.getContentResolver().openInputStream(uri);
Bitmap bmInImg = BitmapFactory.decodeStream(is);
InputStream Vign = this.getResources().openRawResource(R.drawable.p);
Bitmap bmInImg2 = BitmapFactory.decodeStream(Vign);
mPhotoIntArray = new int[bmInImg.getWidth() * bmInImg.getHeight()];
nPhotoIntArray = new int[bmInImg.getWidth() * bmInImg.getHeight()];
vPhotoIntArray = new int[bmInImg2.getWidth() * bmInImg2.getHeight()];
But its showing me below error on this.getContentResolver().openInputStream(uri);
Error :
Unhandled exception type FileNotFoundException
Error come when I use InputStream Vign = this.getResources().openRawResource(R.drawable.p); in the code.
if you have the Uri to the image, you resolve it with content resolver:
InputStream is = context.getContentResolver().openInputStream(uri);
Don't forget to close the stream. (and check for null). context sometime is your activity or "this".
I want the picture to go straight to the ImageView without saving it to gallery if possible. As shown in the screenshot, it will ask to save everytime and will save straight to the gallery. Can this be achieved, or will I have to make my own ImageView camera?
public class Main extends Activity {
ImageView ivPhoto;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ivPhoto = (ImageView) findViewById(R.id.ivPic);
}
public void TakePhoto(View v){
Intent camIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(camIntent,0);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode==0){
Bitmap camImage = (Bitmap) data.getExtras().get("data");
ivPhoto.setImageBitmap(camImage);
}
}
Finally got what I wanted. Thanks guys
public class Main extends Activity {
ImageView ivPhoto;
File myFilesDir;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ivPhoto = (ImageView) findViewById(R.id.ivPic);
myFilesDir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/data/com.example.project/files");
System.out.println (myFilesDir);
myFilesDir.mkdirs();
}
public void TakePhoto(View v){
Intent camIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
camIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(myFilesDir.toString()+"/temp.jpg")));
startActivityForResult(camIntent, 0);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode==0){
try {
Bitmap cameraBitmap;
cameraBitmap = BitmapFactory.decodeFile(myFilesDir + "/temp.jpg");
Bitmap.createBitmap(cameraBitmap);
ivPhoto.setImageBitmap(cameraBitmap);
}
catch(Exception e){
e.printStackTrace();
}
}
}
}
From my understanding you don't want this to be showing up by any media scanner, like the gallery application. What you should actually do is not store it in a root directory like pictures or sdcard, but store it in your applications data folder in the sdcard in Android/data/package/.
You can get this using: http://developer.android.com/reference/android/content/Context.html#getExternalFilesDir(java.lang.String)
File myFilesDir = getExternalFilesDir(null);
OR
File myFilesDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
Note that it will only work on API versions 8 or above.
If you don't want to use the function you can simply just use:
File myFilesDir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/data/" + packageName + "/files");
myFilesDir.mkdirs();
Use my Code. I am taking a picture using camera intent and before saving it to gallery , it is showed to the user with a Save and Cancel Button :-
Call Camera Intent :-
String SD_CARD_TEMP_DIR = Environment.getExternalStorageDirectory() + File.separator +CommonFunction.getDateTime()+".jpg"; // Get File Path
Intent takePictureFromCameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
takePictureFromCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(SD_CARD_TEMP_DIR)));
startActivityForResult(takePictureFromCameraIntent, 123);
onActivityResult : -
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_RESULT)
{
if (resultCode == Activity.RESULT_OK)
{
String galleryImatePath = SD_CARD_TEMP_DIR; // make SD_CARD_TEMP_DIR Global so that you can access it here from camera intent or pass it in put Extra method and retrieve it here
File f = new File(galleryImatePath);
try {
Bitmap cameraBitmap = null;
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = false;
bmOptions.inPurgeable = true;
bmOptions.inBitmap = cameraBitmap;
bmOptions.inMutable = true;
cameraBitmap = BitmapFactory.decodeFile(galleryImatePath,bmOptions);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
cameraBitmap.compress(Bitmap.CompressFormat.JPEG, 50, bos);
//To Rotate image Code
ExifInterface exif = new ExifInterface(galleryImatePath);
float rotation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
System.out.println(rotation);
float rotationInDegrees = exifToDegrees(rotation);
System.out.println(rotationInDegrees);
Matrix matrix = new Matrix();
matrix.postRotate(rotationInDegrees);
final Bitmap rotatedBitmap = Bitmap.createBitmap(cameraBitmap , 0, 0, cameraBitmap.getWidth(), cameraBitmap.getHeight(), matrix, true);
FileOutputStream fos=new FileOutputStream(galleryImatePath);
rotatedBitmap.compress(Bitmap.CompressFormat.JPEG, 50, fos);
fos.write(bos.toByteArray());
cameraBitmap.recycle();
System.gc();
fos.flush();
fos.close();
// To set image in imageview in dialog
Capdialog = new Dialog(AddToDo.this,android.R.style.Theme_NoTitleBar_Fullscreen);
Capdialog.setContentView(R.layout.captiondialog);
Capdialog.setCancelable(false);
TextView cancel = (TextView) Capdialog
.findViewById(R.id.cancel);
TextView done = (TextView) Capdialog.findViewById(R.id.done);
Capdialog.getWindow().setSoftInputMode (WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
ImageView img = (ImageView) Capdialog.findViewById(R.id.image);
img.setImageBitmap(rotatedBitmap);
}
catch(Exception e){}
}
}
}
implement your done and cancel on click listener - what you want to do in them.
My code will capture your image, rotate it in the right direction irrespective of camera rotation and show it to you in a dialog before saving it
Google provided a tutorial on this exact topic: Controlling the Camera
I am new to Android programming and I'm writing an application in Java that opens the camera take a photo and save it. I made it via Intents but I can't see onActivityResult running.
I have tested it into my phone (Samsung Galaxy S) and when I take the photo I receive a preview of that photo having two buttons one Save and the other Cancel. I haven't added something to my code to do this so I think it's something that camera does. I want after capturing the image to run onActivityResult (after I press the Save button on the preview).
But how I'm going to return a result to start onActivityResult after pressing the Button Save on the preview?
I FORGOT to tell that after i press save my entire app is terminated.
Here is my Code
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TakePicButton = (Button) findViewById(R.id.TakePicture);
TakePicButton.setOnClickListener((android.view.View.OnClickListener) this);
}
#Override
public void onDestroy(){
super.onDestroy();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// Image captured and saved to fileUri specified in the Intent
Toast.makeText(this, "Image saved to:\n" + data.getData(), Toast.LENGTH_LONG).show();
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(this, "Picture was not taken", Toast.LENGTH_SHORT);
} else {
Toast.makeText(this, "Picture was not taken", Toast.LENGTH_SHORT);
}
}
public void onClick(View v) {
// TODO Auto-generated method stub
if(v.getId() == R.id.TakePicture){
// create Intent to take a picture and return control to the calling application
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE); // create a file to save the image
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file name
// start the image capture Intent
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
}
}
try the below code, you will have to modify it a bit, it will help you get From Library and From Camera both, the SELECT_PICTURE is used for getting image from library
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case SELECT_PICTURE:
Uri selectedImageUri = data.getData();
filemanagerstring = selectedImageUri.getPath();
selectedImagePath = getPath(selectedImageUri);
if (selectedImagePath != null)
myFile = new File(selectedImagePath);
else if (filemanagerstring != null)
myFile = new File(filemanagerstring);
if (myFile != null) {
Bitmap bmp_fromGallery = decodeImageFile(selectedImagePath);
break;
case CAMERA_REQUEST:
Bitmap bmp_Camera = (Bitmap) data.getExtras().get("data");
break;
default:
break;
}
}