Android - Cropping after Camera and Gallery Intents Gives Strange Results - java

I'm trying to launch an Android camera intent and a choose-photo intent (two buttons, one for take photo, one for choose from gallery) and both need a crop intent launched after them then have the cropped photo returned to my app's activity. I've gone through a bunch of the examples posted elsewhere, but I'm getting strange reults with my implementation.
For the take photo event, it appears to work fine, except after taking a photo and going into crop mode, the wrong photo pops up. Instead of cropping the photo you just took it crops an older photo and I can't figure out where it's coming from. Also, sometimes after finishing the crop intent, it crashes with a nullpointerexception after Parcel.readException (can't always reproduce, but I think it haappens more if you take a picture and crop as quickly as possible).
For the choose photo intent, your gallery pops up as expected but upon choosing a photo all that happens is the message "Saved" is toasted instead of returning to my app's activity with the image. I believe I have a misunderstanding of how the choose photo intent works (I pretty much reused the code for the take photo intent).
In both cases, in crop mode you are still allowed to resize the cropped area despite having specified "scale" = false.
My code is as follows:
public class TestPhotoActivity extends Activity {
private ImageView imageView;
private Uri imageUri;
private int int_Height_crop = 600;
private int int_Width_crop = 600;
public final static int TAKE_PICTURE = 0;
public final static int CHOOSE_PICTURE = 1;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.choose_photo);
imageView = (ImageView) findViewById(R.id.photo);
Button take_photo = (Button) findViewById(R.id.take_photo);
take_photo.setOnClickListener(new View.OnClickListener() {
public void onClick(final View view) {
takePhoto(view);
}
});
Button choose_photo = (Button) findViewById(R.id.choose_photo);
choose_photo.setOnClickListener(new View.OnClickListener() {
public void onClick(final View view) {
choosePhoto(view);
}
});
}
public void takePhoto(View view) {
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE", null);
intent.putExtra("crop", "true");
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
intent.putExtra("outputX", int_Width_crop);
intent.putExtra("outputY", int_Height_crop);
intent.putExtra("scale", false);
intent.putExtra("return-data", true);
File photo = new File(Environment.getExternalStorageDirectory(), System.currentTimeMillis() + ".jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photo));
imageUri = Uri.fromFile(photo);
intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
intent.putExtra("noFaceDetection", true);
startActivityForResult(intent, TAKE_PICTURE);
}
public void choosePhoto(View view) {
Intent intent = new Intent(Intent.ACTION_PICK, null);
intent.setType("image/*");
intent.putExtra("crop", "true");
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
intent.putExtra("outputX", int_Width_crop);
intent.putExtra("outputY", int_Height_crop);
intent.putExtra("scale", false);
intent.putExtra("return-data", true);
File photo = new File(Environment.getExternalStorageDirectory(), System.currentTimeMillis() + "Pic.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photo));
imageUri = Uri.fromFile(photo);
intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
startActivityForResult(intent, CHOOSE_PICTURE);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case TAKE_PICTURE:
Log.d("photo", "requestCode: " + requestCode + "resultCode: " + resultCode + "wanted result: " + Activity.RESULT_OK);
if (resultCode == Activity.RESULT_OK) {
if (data == null) {
Log.w("photo", "Null data, but RESULT_OK, from image picker!");
Toast t = Toast.makeText(this, "No photo picked.", Toast.LENGTH_SHORT);
t.show();
return;
}
final Bundle extras = data.getExtras();
if (extras != null) {
Log.d("photo", "extras is not null");
Uri selectedImage = imageUri;
getContentResolver().notifyChange(selectedImage, null);
ContentResolver cr = getContentResolver();
Bitmap bitmap;
try {
bitmap = android.provider.MediaStore.Images.Media.getBitmap(cr, selectedImage);
Log.d("photo", "data.getAction() is not null. setting image.");
imageView.setImageBitmap(bitmap);
} catch (Exception e) {
Toast.makeText(this, "Failed to load", Toast.LENGTH_SHORT).show();
Log.e("photo", e.toString());
}
}
}
case CHOOSE_PICTURE:
Log.d("photo", "requestCode: " + requestCode + "resultCode: " + resultCode + "wanted result: " + Activity.RESULT_OK);
if(resultCode == RESULT_OK){
Log.d("photo", "resultCode is ok");
if (data == null) {
Log.w("photo", "Null data, but RESULT_OK, from image picker!");
Toast t = Toast.makeText(this, "No photo picked.", Toast.LENGTH_SHORT);
t.show();
return;
}
final Bundle extras = data.getExtras();
if (extras != null) {
Log.d("photo", "extras is not null");
Uri selectedImage = imageUri;
getContentResolver().notifyChange(selectedImage, null);
ContentResolver cr = getContentResolver();
Bitmap bitmap;
try {
bitmap = android.provider.MediaStore.Images.Media.getBitmap(cr, selectedImage);
Log.d("photo", "data.getAction() is not null. setting image.");
imageView.setImageBitmap(bitmap);
} catch (Exception e) {
Toast.makeText(this, "Failed to load", Toast.LENGTH_SHORT).show();
Log.e("photo", e.toString());
}
}
}
}
}
}
Any help is greatly appreciated!
EDIT: I should also note that I'm testing on an LG Optimus LTE, Android 2.3

I think your problem comes from useing System.currentTimeMillis() in the temp file name. This would explain sometimes getting an older file.
I would suggest just reusing the same temp file.
Hope it helps...

Related

Saving path to image

There is a function, adding user image to my app, but I need image to use again, so I chose SQLite Database to save path to image, my database works correctly. So in OnClick method, app show DialogWindow, where user choose image from gallery:
choosePath.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
//Type - image:
photoPickerIntent.setType("image/*");
//Start activity, waiting for result
startActivityForResult(photoPickerIntent, Pick_image);
}
});
Then onActivityResult is called:
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch (requestCode){
case Pick_image:
if(requestCode == RESULT_OK){
try {
final Uri imageUri = imageReturnedIntent.getData();
final InputStream imageStream = getContentResolver().openInputStream(imageUri);
final Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);
Log.e("mLog", "onActivityResult: " + imageStream + " " + imageReturnedIntent + " " + imageUri);
pathToImage = imageUri.toString();
} catch (FileNotFoundException e){
e.printStackTrace();
}
}
}
}
But when I save path in SQlite:
ContentValues cv = new ContentValues();
cv.put("description", description);
cv.put("image_link", pathToImage);
cv.put("category", category[0]);
long res = mDb.insert("favourites", null, cv);
if (res > -1) {
Toast.makeText(getApplicationContext(), "Шаблон добавлен в любимые", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Ошибка", Toast.LENGTH_SHORT).show();
}
I get exception:
E/SQLiteDatabase: Error inserting description=dog image_link=null category=
android.database.sqlite.SQLiteConstraintException: NOT NULL constraint failed: favourites.image_link (code 1299 SQLITE_CONSTRAINT_NOTNULL)
I used debugger, but it didnt help me.
Please help me to solve this problem!
Correct your if condition, that causes your code not running inside if condition and getting pathToImage object null
// you are matching here request code with result status
if(requestCode == RESULT_OK)
//It should be
if(resultCode == RESULT_OK)

Take picture from linear layout and save to gallery

How can I take picture from LinearLayout and save it to gallery? For example my LinearLayout name is ll I want to take picture from ll and save it to the gallery.
I think you mean to take photo from your mobile desktop programmatically ?if so use intent to take photo.you can search the net for intent to take photo.
you can use this block of code.
private static final int TAKE_PICTURE = 1;
private Uri imageUri;
public void takePhoto(View view) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File photo = new File(Environment.getExternalStorageDirectory(), "Pic.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photo));
imageUri = Uri.fromFile(photo);
startActivityForResult(intent, TAKE_PICTURE);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case TAKE_PICTURE:
if (resultCode == Activity.RESULT_OK) {
Uri selectedImage = imageUri;
getContentResolver().notifyChange(selectedImage, null);
ImageView imageView = (ImageView) findViewById(R.id.ImageView);
ContentResolver cr = getContentResolver();
Bitmap bitmap;
try {
bitmap = android.provider.MediaStore.Images.Media
.getBitmap(cr, selectedImage);
imageView.setImageBitmap(bitmap);
Toast.makeText(this, selectedImage.toString(),
Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(this, "Failed to load", Toast.LENGTH_SHORT)
.show();
Log.e("Camera", e.toString());
}
}
}
}

Android API Level 8 Pick up the last taken Photo form specific folder

I would like to take a Photo that was Caputred with my App and send it via SFTP. I'm putting the Photo to an Specific folder:
timeStamp = new SimpleDateFormat("yyyyMMDD_HHmmss").format(new Date());
root = new File(Environment.getExternalStorageDirectory()+ File.separator + "OpenClinica" + File.separator);
root.mkdirs();
sdDir = new File(root, "OC_" + timeStamp + ".jpg");
Now I need to take this picture by a click of a button and send it via SFTP.
I have the classes/methods for SFTP, but I can not get the file selector.
Thank you for Helping
Try this code:
#Override
public void onClick(View v) {
if (v.getId() == findViewById(R.id.ID).getId()){
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Seleccionar vídeo"), PICK_IMAGE);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == PICK_IMAGE && data != null && data.getData() != null) {
Uri _uri = data.getData();
//User had pick an video.
Cursor cursor = getContentResolver().query(_uri, new String[] { android.provider.MediaStore.Images.ImageColumns.DATA }, null, null, null);
cursor.moveToFirst();
//Link to the video
final String imageFilePath = cursor.getString(0);
cursor.close();
}
}
Hope it´s useful!!
Thanks a lot is solved it this way:
protected void startCameraActivity() {
outputFileUri = Uri.fromFile(sdDir);
i = new Intent("android.media.action.IMAGE_CAPTURE");
i.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(i, 0);
}
//Manage everything that happens after the Camera was started
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//
// Write the Captured Image as File
Intent intent = new Intent();
intent.putExtra("uri", sdDir.getPath());
//Grab the Captured Image from the Cache an create the Preview
bmp = BitmapFactory.decodeFile(outputFileUri.getPath());
//Rotates the Preview Image
Matrix matrix=new Matrix();
matrix.postRotate(90);
Bitmap bMapRotate = Bitmap.createBitmap(bmp, 0, 0,bmp.getWidth(),bmp.getHeight(), matrix, true);
//Set the Rotated Image as Preview in the ImageView from the Layout
iv.setImageBitmap(bMapRotate);
setResult(0, intent);
}

Using the camera intent to take a picture without an sdcard

I'm having trouble using the camera when there's no sdcard present.
When there is an sdcard, using the camera is trivial, e.g.
http://www.vogella.com/articles/AndroidCamera/article.html + a plethora of other examples.
However, I need to make my app available to devices which don't have SD cards, (e.g. the Sony Xperia series.) I've tried modifying the code such that I'm using the internal storage (I think):
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File file = new File(getDir("myDirec", Context.MODE_WORLD_WRITEABLE), "tmp_photo_" + String.valueOf(System.currentTimeMillis()) + ".jpg");
file.createNewFile();
mImageCaptureUri = Uri.fromFile(file);
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, mImageCaptureUri);
intent.putExtra("return-data", true);
However, upon result:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intentReturn) {
if (resultCode != RESULT_OK)
return;
String path = mImageCaptureUri.getPath();
Bitmap bitmap = BitmapFactory.decodeFile(path);
...
bitmap is null.
Which leads me to believe that there's some permissions issue....maybe?
I've tried some of the other internal storage options, http://developer.android.com/guide/topics/data/data-storage.html#filesInternal e.g. getFilesDir() but the same result: null bitmap.
Has anyone had any success in using the camera without an sdcard?
Try this. It works..
private Uri imageUri;
public void onClick(View arg0) {
switch (arg0.getId()) {
case R.id.btnImageCapture:
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
File dir = context.getDir("directory", Context.MODE_PRIVATE);
File photo = new File(dir, "Pic.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photo));
imageUri = Uri.fromFile(photo);
startActivityForResult(intent, OPEN_CAMERA);
break;
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case OPEN_CAMERA:
if (resultCode == Activity.RESULT_OK) {
Uri selectedImage = imageUri;
getContentResolver().notifyChange(selectedImage, null);
ImageView imageView = (ImageView) findViewById(R.id.ImageView);
ContentResolver cr = getContentResolver();
Bitmap bitmap;
try {
bitmap = android.provider.MediaStore.Images.Media
.getBitmap(cr, selectedImage);
imageView.setImageBitmap(bitmap);
Toast.makeText(this, selectedImage.toString(),
Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(this, "Failed to load", Toast.LENGTH_SHORT)
.show();
}
}
}
}

capturing image using camera in Android

Hi stackoverflow friends,
I need to take a picture using camera and after takin the picture go to next activity without showing the first activity. And display it in an imageview.
Below is the flow of my application
first activity-> there is button for camera intent->go to the next activity(without showing the fist activity) second activity->there i need to show the image in imageview.
I saw a lot of examples of camera intent nobody explains how to go to the next activity without showing the first and display it in imageview of second.
Any outofmemeory problem occurs while displaying images in imageview repeatedly?
Thanks in advance
In First activity :
Button b=(Button)findViewByid(R.id.button);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
doTakePhotoAction();
}
});
private void doTakePhotoAction() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
mUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(),
"pic_" + String.valueOf(System.currentTimeMillis()) + ".jpg"));
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, mUri);
try {
intent.putExtra("return-data", true);
startActivityForResult(intent, CAMERA_RESULT);
// finish();
} catch (ActivityNotFoundException e) {
e.printStackTrace();
}
}
protected void onActivityResult(int requestCode,
int resultCode, Intent data) {
if (resultCode != RESULT_OK) {
return;
}
if (requestCode == CAMERA_RESULT) {
Intent intent = new Intent(this, nextimage.class);
// here you have to pass absolute path to your file
intent.putExtra("image-path", mUri.getPath());
intent.putExtra("scale", true);
startActivity(intent);
finish();
}
}
In nextimage.class you can set one image view and get the imagepath from putExtra and place it in imageview.
String mImagePath = extras.getString("image-path");
Bitmap mBitmap = getBitmap(mImagePath);
private Uri getImageUri(String path) {
return Uri.fromFile(new File(path));
}
private Bitmap getBitmap(String path) {
Uri uri = getImageUri(path);
InputStream in = null;
try {
in = mContentResolver.openInputStream(uri);
return BitmapFactory.decodeStream(in);
} catch (FileNotFoundException e) {
Log.e(TAG, "file " + path + " not found");
}
return null;
}
place the bitmap in the imageview.you have to create imageview in secondActivity.
use a camera intent....here's a simple code
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.widget.ImageView;
public class CameraIntent extends Activity {
final static int CAMERA_RESULT = 0;
ImageView imv;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Intent i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(i, CAMERA_RESULT);
}
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if (resultCode == RESULT_OK)
{
Get Bundle extras = intent.getExtras();
Bitmap bmp = (Bitmap) extras.get("data");
imv = (ImageView) findViewById(R.id.ReturnedImageView);
imv.setImageBitmap(bmp);
}
}
}
Use Following Code for that, it will solve your problem.
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);
onActivityResult() Method:-
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == CAMERA_PIC_REQUEST) {
bmpImage = (Bitmap) data.getExtras().get("data");
drawable = new BitmapDrawable(bmpImage);
mImageview.setImageDrawable(drawable);
}
}
}

Categories

Resources