When I take a photo by camera app, I add the photo in gallery.
First I create a image file:
private File createImageFile() throws IOException {
Context context = getApplicationContext();
String uuid = Items.get("uuid");
File storageDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
uuid, //prefix
".jpg", //suffix
storageDir //directory
);
mCurrentPhotoPath = "file://" + image.getAbsolutePath();
return image;
}
Then I add it to the gallery.
private void galleryAddPic() {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(mCurrentPhotoPath);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
}
mCurrentPhotoPath is the Uri to that file.
How can I copy this photo into internal storage.
I want to copy that in that storage for the case that the user deletes the image from gallery or something.
You have to call camera intent with secure path so image can not able to view in gallery or any photo app but your own app can access the file.
public static final int CAMERA_REQUEST = 0x000003;
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, setImageUri());
cameraIntent.putExtra("return-data", true);
mActivity.startActivityForResult(cameraIntent, ActivityConstantUtils.CAMERA_REQUEST);
public Uri setImageUri() {
File file = new File(Environment.getExternalStorageDirectory().getPath(), ActivityConstantUtils.STORED_IMAGE_PATH + "/Images/WOMCamera");
if (!file.exists()) {
file.mkdirs();
}
String mCurrentPhotoPath = (file.getAbsolutePath() + "/" + "IMG_" + System.currentTimeMillis() + ".jpg");
return Uri.fromFile(new File(mCurrentPhotoPath));
}
In onActivityResult() you get the image path where captured image stored & hide from gallery and user.
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
//Image from Camera
if (requestCode == ActivityConstantUtils.CAMERA_REQUEST && resultCode == Activity.RESULT_OK) {
}
}
Related
I'm following android developers guide to capture a high quality image and save it into the storage then display it. The issue is after capturing the image I get redirected to the main activity without displaying the preview though the image was created successfully in the storage
public void take_hq_image(View view) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
}
// Continue only if the File was successfully created
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(this,
"com.example.android.fileprovider", photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, HIGH_Q_IMAGE_CAPTURE_REQUEST);
}
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == HIGH_Q_IMAGE_CAPTURE_REQUEST && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap bitmap = (Bitmap) extras.get("data");
HQimageView.setImageBitmap(bitmap);
}
}
Saved image path as a string in currentImagePath variable
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
currentImagePath = image.getAbsolutePath();
return image;
}
Then displayed the preview
Bitmap bitmap = BitmapFactory.decodeFile(currentImagePath);
HQimageView.setImageBitmap(bitmap);
I've written some code in a fragment to open the camera app and once a photo is taken, a photo is saved. I cannot get it to save a full size image, its saving a lower res version. Can anyone spot where I've gone wrong?
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getActivity().getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
mNewPhotoPath = getContext().getExternalFilesDir(Environment.DIRECTORY_PICTURES) + "/" +
photoFile.getName();
} catch (IOException ex) {
// Error occurred while creating the File
}
// Continue only if the File was successfully created
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(getContext(),
"com.example.mmackenz.myholidays.fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
}
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getActivity().getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = image.getAbsolutePath();
return image;
}
This is what I have in my onActivityResult in case that is relevant:
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
File newImage = new File(mNewPhotoPath);
images.add(newImage);
adapter.notifyDataSetChanged();
Photo newPhoto = new Photo(newImage.getAbsolutePath(), newImage.getName(), -1, -1);
DatabaseHandler db = DatabaseHandler.getInstance(getContext());
db.addPhoto(newImage.getAbsolutePath(), newImage.getName(), -1,-1);
}
}
It adds a new file to an array list which is displayed in a recycler view, and also info of the file in a Photos table.
Thanks
I have a problem, that when i have taken an image from camera, image not displaying in imageview.
I created the code by referring the following link
http://developer.android.com/training/camera/photobasics.html
I am posting my code, please have a look,
public void takeImage(View v) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
}
if (photoFile != null) {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "sample_" + timeStamp + "_";
File storageDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = "file:" + image.getAbsolutePath();
galleryAddPic();
return image;
}
private void galleryAddPic() {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(mCurrentPhotoPath);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
if (requestCode == REQUEST_IMAGE_CAPTURE) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
mImageView.setImageBitmap(imageBitmap);
}
}catch (Exception e) {
Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG).show();
}
}
The image captured is storing in SDcard. But not showing in imageview.
Where i have gone wrong. I have tried a lot. But no result. Is there any way to solve this issue.
this works for me:
Bitmap myBitmap = BitmapFactory.decodeFile(imagePath);
image.setImageBitmap(myBitmap);
You don't need to create the temp file, just put the Uri in the intent. After the capture, check the file existence of that Uri. If it exists, capture has been done successfully.
I´ve been struggling with this for a few days now and other answers posted in similar questions here on stackoverflow haven´t helped me.
What I want to do is set a custom ArrayAdapter to my ListView and inside this adapter I want to set an onClickListener to a button that appears in every item. Then I want the user to pick whether he wants to take a picture with the camera or choose a picture from the gallery. Then I want the picture to save in the app´s own folder inside Gallery. However, although the custom folder is created and visible in Gallery, the picture itself is stored in the Camera folder and I can see a broken file in the custom folder.
I´ve read photobasics on the devsite http://developer.android.com/training/camera/photobasics.html, but it did not help much.
I implemented the onActivityResult inside my Fragment but the Uri path is different fro the one created in the adapter.
Here is the code:
In ArrayAdapter:
photoPicker.setOnClickListener(new View.OnClickListener()
{
#Override public void onClick(View v)
{
// Camera.
final List<Intent> cameraIntents = new ArrayList<Intent>();
final Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
final PackageManager packageManager = mContext.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);
}
// 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, "Vyber zdroj");
// Add the camera options.
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, cameraIntents.toArray(new Parcelable[]{}));
if (chooserIntent.resolveActivity(mContext.getPackageManager()) != null)
{
// Create the File where the photo should go
File photoFile = null;
try
{
photoFile = createImageFile();
}
catch (IOException ex)
{
// Error occurred while creating the File
}
// Continue only if the File was successfully created
if (photoFile != null)
{
chooserIntent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photoFile));
Log.i(TAG,"uri from file:"+Uri.fromFile(photoFile).toString());
chooserIntent.putExtra("path",mCurrentPhotoPath);
fragment.startActivityForResult(chooserIntent, FlowListUtils.getIdFromDate(experience.getDate()));
}
}
}
});
private File createImageFile() throws IOException
{
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
String storagePath = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES).getPath()+"/MyApp";
File storageDir = new File(storagePath);
storageDir.mkdirs();
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = "file:" + image.getAbsolutePath();
Log.i(TAG,"mCurrent Photo Path in adapter:"+mCurrentPhotoPath);
return image;
}
This code is in my Fragment
#Override public void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
ExperienceAdapter.dateForPicture = requestCode;
ExperienceAdapter.uriForPicture = data.getData();
galleryAddPic(path);
}
private void galleryAddPic(String path)
{
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(ExperienceAdapter.mCurrentPhotoPath);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
getActivity().sendBroadcast(mediaScanIntent);
}
The path I add to the intent is file:/storage/emulated/0/Pictures/MyApp/JPEG_20140626_133228_1332202116.jpg
but suddenly changes to content://media/external/images/media/6273 in the Intent return by onActivityResult.
Where am I going wrong?
Here is the function to save the Image,
public static String saveImageInExternalCacheDir(Context context, Bitmap bitmap, String myfileName) {
String fileName = myfileName.replace(' ', '_') + getCurrentDate().toString().replace(' ', '_').replace(":", "_");
String filePath = (context.getExternalCacheDir()).toString() + "/" + fileName + ".jpg";
try {
FileOutputStream fos = new FileOutputStream(new File(filePath));
bitmap.compress(Bitmap.CompressFormat.JPEG, 85, fos);
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
return filePath;
}
You have a really good example here -> Taking Photos Simply.
When you go save with createImageFile function you can choose your directory url:
private File createImageFile() throws IOException {
// Create an image file name
timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);]
File image = File.createTempFile(
imageFileName,
".jpg",
storageDir
);
mCurrentPhotoPath = "file:" + image.getAbsolutePath();
return image;
}
I think this is what you need!
I just want to save a picture in my Imagefolder in my phone.
I have got 2 examples which I tried.
1. Example
My app crashes when I activate the onClick Method:
public void onClick(View arg0) {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, 1337);
}});
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if( requestCode == 1337)
{
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
MediaStore.Images.Media.insertImage(getContentResolver(),file.getAbsolutePath(),file.getName(),file.getName());
}
else
{
Toast.makeText(AndroidCamera.this, "Picture NOt taken", Toast.LENGTH_LONG);
}
super.onActivityResult(requestCode, resultCode, data);
}
2. Example
Before I saved my taken Picture with Uri. But it saved my picture in a folder, which I can only access on my PC or with a FileApp. I don´t know how I can change the Path direction with Uri to my existing default image folder in my phone.
Uri uriTarget = getContentResolver().insert(Media.EXTERNAL_CONTENT_URI, new ContentValues());
This is how I manage with saving images to specified imagefolder
When starting camera intent I define path and directory, where my image should be saved, and pass this as intetn extra when starting camera:
private void startCameraIntent() {
//create file path
final String photoStorePath = getProductPhotoDirectory().getAbsolutePath();
//create file uri
final Uri fileUri = getPhotoFileUri(photoStorePath);
//create camera intent
final Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//put file ure to intetn - this will tell camera where to save file with image
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
// start activity
startActivityForResult(cameraIntent, REQUEST_CODE_PHOTO_FROM_CAMERA);
//start image scanne to add photo to gallery
addProductPhotoToGallery(fileUri);
}
And here are some of helper methods used in code above
private File getProductPhotoDirectory() {
//get directory where file should be stored
return new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES),
"myPhotoDir");
}
private Uri getPhotoFileUri(final String photoStorePath) {
//timestamp used in file name
final String timestamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.US).format(new Date());
// file uri with timestamp
final Uri fileUri = Uri.fromFile(new java.io.File(photoStorePath
+ java.io.File.separator + "IMG_" + timestamp + ".jpg"));
return fileUri;
}
private void addProductPhotoToGallery(Uri photoUri) {
//create media scanner intetnt
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
//set uri to scan
mediaScanIntent.setData(photoUri);
//start media scanner to discover new photo and display it in gallery
this.sendBroadcast(mediaScanIntent);
}