final List<Intent> cameraIntents = new ArrayList<Intent>();
final Intent captureIntent = new Intent(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);
cameraIntents.add(intent);
}
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI); galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
final Intent chooserIntent = Intent.createChooser(galleryIntent, "Select Source");
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, cameraIntents.toArray(new Parcelable[]{}));
startActivityForResult(chooserIntent, 1);
So , thats How I call to open either camera or take a picture. How i read them on onactivityresult????check below the code. The problem, when image chosen from photos it works, when taken from camera it works. But when chosen from gallery folder, it doesnt work for some reason. Also some of clients are reporting me problem on sony xperia e4 phones.
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
if (resultCode == Activity.RESULT_OK && requestCode == 1
) {
Bitmap bm = null;
try
{
Bundle extras = data.getExtras();
bm = (Bitmap) extras.get("data");
}
catch(Exception e)
{
try
{
Uri selectedImage = data.getData();
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = false;
options.inPreferredConfig = Bitmap.Config.RGB_565;
options.inDither = true;
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(
selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex);
cursor.close();
Common.setBitmap(null);
bm = BitmapFactory.decodeFile(filePath);
BitmapFactory.decodeFile(Common.getRealPathFromURI(data.getData(), rootView.getContext()), bounds);
if(bm == null)
bm = BitmapFactory.decodeFile(Common.getRealPathFromURI(selectedImage, AddStoreActivity.this), options);
if(bm == null)
bm = MediaStore.Images.Media.getBitmap(getContentResolver(), selectedImage);
}
catch(Exception e1)
{
}
}
}
} catch (Exception e) {
}
}
public static String getRealPathFromURI(Uri contentURI, Context cont) {
Cursor cursor = cont.getContentResolver().query(contentURI, null, null, null, null);
if (cursor == null) { // Source is Dropbox or other similar local file path
return contentURI.getPath();
} else {
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaColumns.DATA);
return cursor.getString(idx);
}
}
This is how I do this and it works:
private void displayAddPhotoDialog() {
final CharSequence[] items = getResources().getStringArray(R.array.photo_dialog_options);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(getResources().getString(R.string.photo_dialog_title));
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (item == TAKE_PHOTO_OPTION) {
dispatchTakePictureIntent();
} else if (item == CHOOSE_FROM_LIBRARY_OPTION) {
dispatchPickImageIntent();
} else if (item == CANCEL_OPTION) {
dialog.dismiss();
}
}
});
builder.show();
}
protected void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getActivity().getPackageManager()) != null) {
File photoFile = null;
try {
photoFile = createImageFile();
imageUri = Uri.fromFile(photoFile);
} catch (IOException ex) {
Toast.makeText(getActivity(), ex.toString(), Toast.LENGTH_SHORT).show();
}
if (photoFile != null) {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(takePictureIntent, CAMERA_REQUEST_CODE);
}
} else {
Toast.makeText(getActivity(), R.string.no_camera_error_message, Toast.LENGTH_SHORT).show();
}
}
protected void dispatchPickImageIntent() {
Intent intent = new Intent();
intent.setType("image/*");
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
intent.setAction(Intent.ACTION_GET_CONTENT);
} else {
intent.setAction(Intent.ACTION_OPEN_DOCUMENT);
}
startActivityForResult(Intent.createChooser(intent, getString(R.string.select_picture)), GALLERY_REQUEST_CODE);
}
And your onActivityResult method should look like this:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
photoReceivedFromCamera = true;
getActivity().getContentResolver().notifyChange(imageUri, null);
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
mediaScanIntent.setData(imageUri);
getActivity().sendBroadcast(mediaScanIntent);
//do want you want with the uri(taken photo)
} else if (requestCode == CAMERA_REQUEST_CODE && resultCode == Activity.RESULT_CANCELED) {
//The user cancelled the take picture action...
if (!photoReceivedFromCamera) {
//If the user has not previously taken a picture,
//this means he is cancelling the take photo process
onCancelTakePicture();
}
} else if (requestCode == GALLERY_REQUEST_CODE && data != null && data.getData() != null) {
Uri uri = data.getData();
//do want you want with the uri(selected image)
}
}
Related
I have followed some examples on SO of how to retrive an image from Camera or Gallary. The camera part works, but the gallary part dosn't. The code seems very diffuclt to understand for me, so I dont know what exactly to look after.
I also have the needed permissions in my manifest.
Here is a video of the problem: https://www.youtube.com/watch?v=OOoY1y4W86w
ImagePicker(View V), intent/choosers, files, URIS
public void ImagePicker(View v) {
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
if (PackageManager.PERMISSION_GRANTED == ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) && PackageManager.PERMISSION_GRANTED == ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)) {
final File rootdir = new File(Environment.getExternalStorageDirectory() + File.separator + "TravelDiary" + File.separator);
rootdir.mkdirs();
final String filename = "img_" + System.currentTimeMillis() + ".jpg";
final File sdImageMainDirecotry = new File(rootdir, filename);
outputFileUri = Uri.fromFile(sdImageMainDirecotry);
Log.d("TAG", "IM HERE 1");
//camera
final List<Intent> cameraIntents = new ArrayList<>();
final Intent CameraCaptureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
final PackageManager packageManager = getPackageManager();
final List<ResolveInfo> listcam = packageManager.queryIntentActivities(CameraCaptureIntent, 0);
Log.d("TAG", "IM HERE 2");
for (ResolveInfo res : listcam) {
final String packageName = res.activityInfo.packageName;
final Intent intent = new Intent(CameraCaptureIntent);
intent.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
intent.setPackage(packageName);
intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
cameraIntents.add(intent);
Log.d("TAG", "IM HERE 3");
}
//Gallary
final Intent imageChooser = new Intent();
imageChooser.setType("image/*");
imageChooser.setAction(Intent.ACTION_GET_CONTENT);
// Chooser of filesystem options.
final Intent chooserIntent = Intent.createChooser(imageChooser, "Select Source");
// Add the camera options.
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, cameraIntents.toArray(new Parcelable[cameraIntents.size()]));
startActivityForResult(chooserIntent, SELECT_FROM_GALLARY);
} else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
}
} else {
Toast.makeText(this, "External storage not available", Toast.LENGTH_SHORT).show();
}
}
onActivityResult():
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_FROM_GALLARY) {
final boolean isCamera;
if (data == null) {
isCamera = true;
} else {
final String action = data.getAction();
if (action == null) {
isCamera = false;
} else {
isCamera = action.equals(MediaStore.ACTION_IMAGE_CAPTURE);
}
}
Uri selectedImageUri;
if (isCamera) {
selectedImageUri = outputFileUri;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 8;
final Bitmap bitmap = BitmapFactory.decodeFile(selectedImageUri.getPath(), options);
Drawable drawable = new BitmapDrawable(getResources(), bitmap);
pic.setBackground(drawable);
} else {
selectedImageUri = data == null ? null : data.getData();
Log.d("ImageURI", selectedImageUri.getLastPathSegment());
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 8;
try {
InputStream input = getContentResolver().openInputStream(selectedImageUri);
final Bitmap bitmap = BitmapFactory.decodeStream(input, null, options);
Drawable drawable = new BitmapDrawable(getResources(), bitmap);
pic.setBackground(drawable);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
}
}
Use below code to pick image from Gallery.
Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/*");
//Here PICK_FROM_GALLERY is a requestCode
startActivityForResult(intent, PICK_FROM_GALLERY);
In onActivityResult():
if (resultCode == Activity.RESULT_OK && requestCode == PICK_FROM_GALLERY) {
if (data.getData() != null) {
mImageUri = data.getData();
} else {
//showing toast when unable to capture the image
Debug.toastValid(context, "Unable to upload Image Please Try again ...");
}
}
Problem: The user may take/select up to 3 photos. I'm having trouble in figuring out how to fill the 3 cases; I'm not sure how I could do to retrieve the corresponding ImageView ID.
I tried the putextra since I'm using
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE), but it seems that it's not possible to use the putextra method (I don't retrieve any extra)
So let me share the code with you and feel free to let me know if you would proceed differently. Thanks a lot!
So here I'm catching the click event and passing the V.getID to the method that will handle the actions related to selecting/taking photos.
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.add_item_give_button:
checkAddedItem();
break;
case R.id.add_item_image_1:
selectImage(v.getId());
break;
case R.id.add_item_image_2:
selectImage(v.getId());
break;
case R.id.add_item_image_3:
selectImage(v.getId());
break;
}
}
The selectImage method is called and will handle the alertDialog that will ask if the user wants either to take a picture or to select one. I'm trying to pass the ID in the putExtra method, but nothing is received in the startActivityForResult
public void selectImage(final int imageViewID){
final CharSequence[] options = {getString(R.string.cameral_select_photo_label), getString(R.string.camera_take_photo_label), getString(R.string.common_cancel_label)};
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(getString(R.string.camera_dialog_title_label));
builder.setItems(options, new DialogInterface.OnClickListener() {
#TargetApi(Build.VERSION_CODES.LOLLIPOP_MR1)
#Override
public void onClick(DialogInterface dialog, int which) {
if(options[which].equals(getString(R.string.camera_take_photo_label))){
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra("ImageViewID", imageViewID);
startActivityForResult(intent, REQUEST_CAMERA);
}
else if(options[which].equals(getString(R.string.cameral_select_photo_label))){
Utils.verifyStoragePermissions(getActivity());
Intent intent = new Intent(
Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI
);
intent.setType("image/*");
startActivityForResult(
Intent.createChooser(intent, getResources().getText(R.string.camera_select_image)),SELECT_FILE);
}
else if(options[which].equals(getString(R.string.common_cancel_label))){
dialog.dismiss();
}
}
});
builder.show();
}
In the startActivityForResult, I don't receive the ImageViewID. So for now, I'm just putting the image in the first ImageView since I'm not able to retrieve the right ID.
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == Activity.RESULT_OK){
if(requestCode == REQUEST_CAMERA){
Log.d("Data content", String.valueOf(data));
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
File destination = new File(Environment.getExternalStorageDirectory(),
System.currentTimeMillis() + ".jpg");
FileOutputStream fo;
try {
destination.createNewFile();
fo = new FileOutputStream(destination);
fo.write(bytes.toByteArray());
fo.close();
} catch (IOException e) {
e.printStackTrace();
}
itemPic1.setImageBitmap(thumbnail);
} else if (requestCode == SELECT_FILE){
Log.d("imageViewOrigin", String.valueOf(data.getIntExtra("imageViewID", 0)));
Uri selectedImageUrl = data.getData();
String[] projection = {MediaStore.MediaColumns.DATA};
CursorLoader cursorLoader = new CursorLoader(getContext(), selectedImageUrl, projection, null, null, null);
Cursor cursor = cursorLoader.loadInBackground();
int column_index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
cursor.moveToFirst();
String selectedImagePath = cursor.getString(column_index);
Bitmap bm;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(selectedImagePath, options);
final int REQUIRED_SIZE = 200;
int scale = 1;
while(options.outWidth / scale / 2 >= REQUIRED_SIZE && options.outHeight / scale / 2 >= REQUIRED_SIZE)
scale += 2;
options.inSampleSize = scale;
options.inJustDecodeBounds = false;
bm = BitmapFactory.decodeFile(selectedImagePath, options);
itemPic1.setImageBitmap(bm);
}
}
}
I would recommend setting tags on the ImageViews. Follow the link, its a similar issue What is the main purpose of setTag() getTag() methods of View?. Let me know if you need more help!
Try this way :
private void openImageIntent(int IMAGE_TYPE) {
// Determine Uri of camera image to save.
final File root = new File(Environment.getExternalStorageDirectory() + File.separator + "mycapturedImage" + File.separator);
root.mkdirs();
final String fname = getUniqueImageFilename();
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, "Choisir une Source");
// Add the camera options.
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, cameraIntents.toArray(new Parcelable[cameraIntents.size()]));
startActivityForResult(chooserIntent, IMAGE_TYPE);
}
Then retrieve each Image like this :
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_CANCELED) {
if (resultCode == RESULT_OK) {
if (requestCode == FIRST_IMAGE_INTENT) {
final boolean isCamera;
if (data == null) {
isCamera = true;
} else {
final String action = data.getAction();
if (action == null) {
isCamera = false;
} else {
isCamera = action.equals(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
}
}
if (isCamera) {
selectedCaptureUri = outputFileUri;
} else {
selectedCaptureUri = data == null ? null : data.getData();
}
//Display image here
} else if (requestCode == SECOND_PICTURE_INTENT) {...}
Right now I have an imageview. Clicking on the imageview I can get the option to select the gallery/camera intent.selecting on the required intent and the required picture I get the image in the imageview.This works fine for one single image.
How to get more than one picture.I mean the imageview[].Is there any code on this available?
Start Intent with EXTRA_ALLOW_MULTIPLE
Intent intent = new Intent( );
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
startActivityForResult(Intent.createChooser(intent,
"select multiple images"), PICK_IMAGE_MULTIPLE);
On receiving side
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if(resultCode == Activity.RESULT_OK){
if(requestCode == PICK_IMAGE_MULTIPLE){
String[] imagesPath = data.getStringExtra("data").split("\\|");
}
}
}
thanks for the response but here is my code.Now please let me know how to go ahead to have multiple images shown up in multiple imageviews.Also let me know if I need a placeholder like gridview for that?
ImageView image_view = new ImageView(this);
image_view.setId(field_id);
Uri selectedImage = Uri.parse(field_val);
String[] filePath = { MediaStore.Images.Media.DATA };
String picturePath;
Cursor c = getContentResolver().query(selectedImage,
filePath, null, null, null);
c.moveToFirst();
if(c.moveToFirst() && c.getCount() >= 1)
{
int columnIndex = c.getColumnIndex(filePath[0]);
picturePath = c.getString(columnIndex);
c.close();
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmapOptions.inSampleSize = 20;
Bitmap thumbnail = (BitmapFactory.decodeFile(
picturePath, bitmapOptions));
image_view.setImageBitmap(thumbnail);
image_view.setTag(selectedImage);
}
else {
image_view.setImageDrawable(getResources().getDrawable(
R.drawable.camera_launcher));
}
image_view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
getImage();
}
});
private void getImage() {
final CharSequence[] options = { "Take Photo", "Choose from Gallery",
"Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(
this);
builder.setTitle("Add Photo!");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (options[item].equals("Take Photo")) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, 1);
} else if (options[item].equals("Choose from Gallery")) {
Intent intent = new Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 2);
} else if (options[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
Bundle extras = data.getExtras();
try {
((ImageView) findViewById(R.id.imageid)).setImageBitmap((Bitmap) extras
.get("data"));
((ImageView) findViewById(R.id.imageid))).setTag(R.string.imgtag,
data.getDataString());
} catch (Exception e) {
e.printStackTrace();
}
} else if (requestCode == 2) {
Uri selectedImage = data.getData();
String[] filePath = { MediaStore.Images.Media.DATA };
String picturePath;
Cursor c = getContentResolver().query(selectedImage, filePath,
null, null, null);
c.moveToFirst();
int columnIndex = c.getColumnIndex(filePath[0]);
picturePath = c.getString(columnIndex);
c.close();
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmapOptions.inSampleSize = 20;
Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath,
bitmapOptions));
((ImageView) findViewById(R.id.imageid))).setImageBitmap(thumbnail);
((ImageView) findViewById(R.id.imageid))).setTag(R.string.imgtag,
selectedImage.toString());
}
}
}
sometime i running App on my phone.problem is when i click Ok button after camera was pick photo up,at this moment!App' stop running!in fact,i wanna see Pic on another Activity!Is
take picture:
private void takePhoto() {
String SDState = Environment.getExternalStorageState();
if (SDState.equals(Environment.MEDIA_MOUNTED)) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
ContentValues values = new ContentValues();
photoUri = getActivity().getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, photoUri);
startActivityForResult(intent, SELECT_PIC_BY_TACK_PHOTO);
if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
Toast.makeText(getActivity(), R.string.take_photo_rem,
Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(getActivity(), R.string.takePhoto_msg,
Toast.LENGTH_LONG).show();
}
}
album:
private void pickPhoto() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, SELECT_PIC_BY_PICK_PHOTO);
}
onActivityResult: user intent send image uri
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
doPhoto(requestCode, data);
}
super.onActivityResult(requestCode, resultCode, data);
}
private void doPhoto(int requestCode, Intent data) {
if (requestCode == SELECT_PIC_BY_PICK_PHOTO) {
if (data == null) {
Toast.makeText(getActivity(), R.string.photo_err,
Toast.LENGTH_LONG).show();
return;
}
photoUri = data.getData();
if (photoUri == null) {
Toast.makeText(getActivity(), R.string.photo_err,
Toast.LENGTH_LONG).show();
return;
}
}
String[] pojo = { MediaStore.Images.Media.DATA };
Cursor cursor = getActivity().managedQuery(photoUri, pojo, null, null,
null);
if (cursor != null) {
int columnIndex = cursor.getColumnIndexOrThrow(pojo[0]);
cursor.moveToFirst();
picPath = cursor.getString(columnIndex);
try {
if (Integer.parseInt(Build.VERSION.SDK) < 14) {
cursor.close();
}
} catch (Exception e) {
Log.e(TAG, "error:" + e);
}
}
Log.i(TAG, "imagePath = " + picPath);
if (picPath != null) {
Intent startEx = new Intent(getActivity(), PhotoPre.class);
Bundle bundle = new Bundle();
bundle.putString(SAVED_IMAGE_DIR_PATH, picPath);
startEx.putExtras(bundle);
startActivity(startEx);
} else {
Toast.makeText(getActivity(), R.string.photo_err, Toast.LENGTH_LONG)
.show();
}
}
preview image Activity!is getIntent() seted null?
Bundle bundle = getIntent().getExtras();
picPath = bundle.getString(KEY_PHOTO_PATH);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
bm = BitmapFactory.decodeFile(picPath, options);
1 - start camera for take image
Intent cameraIntent = new Intent( android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
File imagesFolder = new File(Environment .getExternalStorageDirectory(), "MyImages");
imagesFolder.mkdirs();
File image = new File(imagesFolder, Const.dbSrNo + "image.jpg");
Uri uriSavedImage = Uri.fromFile(image);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
2 - write below code in "onActivityResult"
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
File imgFile = new File(Environment.getExternalStorageDirectory(),
"/MyImages/");
/*photo = BitmapFactory.decodeFile(imgFile.getAbsolutePath() + "/"
+ Const.dbSrNo + "image.jpg");*/
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 4;
options.inPurgeable=true;
Bitmap bm = BitmapFactory.decodeFile(imgFile.getAbsolutePath() + "/"
+ Const.dbSrNo + "image.jpg",options);
imageView2.setImageBitmap(bm);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100, baos); //bm is the bitmap object
byteImage_photo = baos.toByteArray();
Const.imgbyte=byteImage_photo;
3 - generate one java file Const.java
public class Const {
public static byte[] imgbyte = "";
}
4 - now display that image in your activity using
byte[] mybits=Const.imgbyte;
BitmapFactory.Options options = new BitmapFactory.Options();
Bitmap bitmap = BitmapFactory.decodeByteArray(mybits, 0, mybits.length, options);
yourImageview.setImageBitmap(bitmap);
This code worked on samsung before but now that i'm using Nexus One with Android 2.3.6, it's crashing as soon as I take a picture and click ok or choose a photo from gallery. Stacktrace shows a null pointer exception on the Uri.
My code for the activating the camera is as follows:
public void activateCamera(View view){
Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// start the image capture Intent
startActivityForResult(i, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if ((requestCode == CHOOSE_IMAGE_ACTIVITY_REQUEST_CODE || requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)
&& resultCode == RESULT_OK && null != data) {
selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
Bitmap bits = null;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = inSampleSize;
try {
bits = BitmapFactory.decodeStream(new FileInputStream(picturePath),null,options);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Any idea what could be the problem?
Thanks!
You have to tell the camera, where to save the picture and remeber the uri yourself:
private Uri mMakePhotoUri;
private File createImageFile() {
// return a File object for your image.
}
private void makePhoto() {
try {
File f = createImageFile();
Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
mMakePhotoUri = Uri.fromFile(f);
i.putExtra(MediaStore.EXTRA_OUTPUT, mMakePhotoUri);
startActivityForResult(i, REQUEST_MAKE_PHOTO);
} catch (IOException e) {
Log.e(TAG, "IO error", e);
Toast.makeText(getActivity(), R.string.error_writing_image, Toast.LENGTH_LONG).show();
}
}
#Override
public void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
switch (requestCode) {
case REQUEST_MAKE_PHOTO:
if (resultCode == Activity.RESULT_OK) {
// do something with mMakePhotoUri
}
return;
default: // do nothing
super.onActivityResult(requestCode, resultCode, data);
}
}
You should save the value of mMakePhotoUri over instance states withing onCreate() and onSaveInstanceState().
Inject this extra into the Intent that called onActivityResult and the system will do all the heavy lifting for you.
File f = createImageFile();
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
Doing this makes it as easy as this to retrieve the photo as a bitmap.
private void handleSmallCameraPhoto(Intent intent) {
Bundle extras = intent.getExtras();
mImageBitmap = (Bitmap) extras.get("data");
mImageView.setImageBitmap(mImageBitmap);
}
dont pass any extras, just define the path where you have placed or saved the file directly in onActivityResult
public void openCamera() {
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
file = createImageFile();
boolean isDirectoryCreated = file.getParentFile().mkdirs();
Log.d("", "openCamera: isDirectoryCreated: " + isDirectoryCreated);
if (Build.VERSION.SDK_INT >= 23) {
tempFileUri = FileProvider.getUriForFile(getActivity().getApplicationContext(),
"com.scanlibrary.provider", // As defined in Manifest
file);
} else {
tempFileUri = Uri.fromFile(file);
}
try
{
cameraIntent.putExtra("return-data", true);
startActivityForResult(cameraIntent, ScanConstants.START_CAMERA_REQUEST_CODE);
}
catch (Exception e)
{
}
}
private File createImageFile() {
clearTempImages();
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new
Date());
File file = new File(ScanConstants.IMAGE_PATH, "IMG_" + timeStamp +
".jpg");
fileUri = Uri.fromFile(file);
return file;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Bitmap bitmap = null ;
if (resultCode == Activity.RESULT_OK ) {
try {
if (Build.VERSION.SDK_INT >= 23) {
tempFileUri = FileProvider.getUriForFile(getActivity().getApplicationContext(),
"com.scanlibrary.provider", // As defined in Manifest
file);
} else {
tempFileUri = Uri.fromFile(file);
}
bitmap = getBitmap(tempFileUri);
bitmap = getBitmap(data.getData());
} catch (Exception e) {
e.printStackTrace();
}
} else {
getActivity().finish();
}
if (bitmap != null) {
postImagePick(bitmap);
}
}