private static final int CAMERA_REQUEST = 1337;
private void showCamera() {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra("category", "camera");
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
I used this code to pick an image from the camera. and this is my activity result
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST ) {
filePath = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), filePath);
imageView.setImageBitmap(bitmap);
Toast.makeText(this, data.getDataString(), Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
}
else if (requestCode == CAMERA_REQUEST) {
filePath = data.getData();
Log.i("hello", "REQUEST cALL");
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), filePath);
imageView.setImageBitmap(bitmap);
} catch (Exception e) {
Log.i("hello", "Exception" + e.getMessage());
}
}
the camera is fine. and I can capture it
but why imageview cant pick the photos from camera?
but if I am picking from storage the imageview can change the image.
can you see the false code?
To use image file path you have to do like below
1) Write a method to create an image file
String currentPhotoPath;
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
currentPhotoPath = image.getAbsolutePath();
return image;
}
2) Call camera intent
private void showCamera() {
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
}
// 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, REQUEST_TAKE_PHOTO);
}
}
}
3) Now, you need to configure the FileProvider. In your app's manifest, add a provider to your application:
<application>
...
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="${applicationId}.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/file_paths"></meta-data>
</provider>
...
</application>
4) create a resourse file res/xml/file_paths.xml
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="my_images"
path="Android/data/com.example.package.name/files/Pictures" />
</paths>
Note: Make sure that you replace com.example.package.name with the actual package name of your app.
5) Obtain the imageFilePath
if (requestCode == CAMERA_REQUEST) {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), currentPhotoPath);
imageView.setImageBitmap(bitmap);
// or you can use Glide to show image
Glide.with(this).load(currentPhotoPath).into(imageView);
}
Hope it works as you expect. for details you can see google Official documents!
Try this, Hope it will help you.
if (requestCode == CAMERA_REQUEST) {
Bitmap bitmap= (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(bitmap);
}
data.getData();
This one doesnt give you a filepath of the captured image
You can follow this one
Getting path of captured image in Android using camera intent
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
//get the URI of the bitmap from camera result
Uri uri = getImageUri(getApplicationContext(), photo);
// convert the URI to its real file path.
String filePath = getRealPathFromURI(uri);
}
This method gets the URI of the bitmap that you can use to convert it to a file path
public Uri getImageUri(Context inContext, Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
return Uri.parse(path);
}
this method converst a URI to a file path
public String getRealPathFromURI(Uri uri) {
String path = "";
if (getContentResolver() != null) {
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
path = cursor.getString(idx);
cursor.close();
}
}
return path;
}
Related
I am trying to create an application that captures an image and stores it into my internal storage. When I change my codefrom File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES); to File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM); (due to absence of SD card on my phone), it does not open the camera and a file is stored in my DCIM folder. The file stored will be have an error "File format isn't supported or files are corrupted". If I use Environment.DIRECTORY_PICTURES instead it shows a preview of the camera and imageView but no files will be stored.
I am new and any help is greatly appreciated. Thanks in advance.
My code is as shown below
public static final int REQUEST_IMAGE_CAPTURE =1;
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1) {
File imgFile = new File(mCurrentPhotoPath);
if (imgFile.exists()) {
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
ImageView myImage = (ImageView) findViewById(R.id.imageViewID);
myImage.setImageBitmap(myBitmap);
}
}
}
String mCurrentPhotoPath;
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 storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
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;
}
static final int REQUEST_TAKE_PHOTO = 1;
void dispatchTakePictureIntent() {
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, REQUEST_TAKE_PHOTO);
}
}
}
}
I have a URI that contains "0/data/app/data/croppedimage.jpg" and I want to save that in internal storage with the new folder with my file name like "/storage/emulated/0/myfolder/myimage.jpg" from onActivity result.
The code is given below,
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
Uri resultUri = result.getUri();}}
I have tried with FileOutputStream but myImage file crashes or broken.
code below,
File folderPath = new File(Environment.getExternalStorageDirectory() + "/OCR");
if (!folderPath.exists()) {
if (folderPath.mkdir()) ; //directory is created;
} else {
File photo = new File("/storage/emulated/0/myfolder/myimage.jpg");
try {
FileOutputStream fileOutputStream = new FileOutputStream(photo);
fileOutputStream.write(Integer.parseInt(resultUri.toString()));
fileOutputStream.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
I think you are using image crop library. In this case you can use FileProviders concept like this
You should append your package name to .fileprovider like com.yourpackagename.fileprovider
add this to AndroidManifest.xml
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.yourpackagename.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/provider_path"/>
</provider>
inside res folder create xml sub folder and inside this sub folder add this file
provider_path.xml
<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-path name="/storage/emulated/0" path="."/>
</paths>
add this as global variable inside your activity
private static final String CAPTURE_IMAGE_FILE_PROVIDER = "com.yourpackage.name.fileprovider";
And then change your startCropImageActivity() method like this
private void startCropImageActivity(Uri imageUri)
{
File file = null;
try
{
file = createImageFile();
Uri mUri = FileProvider.getUriForFile(this,
CAPTURE_IMAGE_FILE_PROVIDER, file);
CropImage.activity(imageUri)
.setGuidelines(CropImageView.Guidelines.ON)
.setMultiTouchEnabled(true)
.setAllowFlipping(false)
.setAspectRatio(1, 1)
.setRequestedSize(350, 350)
.setMinCropResultSize(350, 350)
.setMaxCropResultSize(800, 800)
.setOutputCompressFormat(Bitmap.CompressFormat.PNG)
.setOutputCompressQuality(90)
.setOutputUri(mUri)
.start(this);
}
catch (IOException e)
{
e.printStackTrace();
}
}
private File createImageFile() throws IOException
{
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "MYAPPNAME-" + timeStamp + ".jpg";
File mediaStorageDir = new File(Environment.getExternalStorageDirectory(),
"YourAppFolder");
File storageDir = new File(mediaStorageDir + "/Profile_Images");
if (!storageDir.exists())
{
storageDir.mkdirs();
}
File image = new File(storageDir, imageFileName);
return image;
}
and finally
#SuppressLint("NewApi")
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
// handle result of pick image chooser
if (requestCode == CropImage.PICK_IMAGE_CHOOSER_REQUEST_CODE && resultCode == Activity.RESULT_OK)
{
Uri imageUri = CropImage.getPickImageResultUri(this, data);
// For API >= 23 we need to check specifically that we have permissions to read external storage.
if (CropImage.isReadExternalStoragePermissionsRequired(this, imageUri))
{
// request permissions and handle the result in onRequestPermissionsResult()
mCropImageUri = imageUri;
requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 0);
}
else
{
// no permissions required or already grunted, can start crop image activity
startCropImageActivity(imageUri);
}
}
// handle result of CropImageActivity
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE)
{
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK)
{
profileImageFilepath = result.getUri().getPath();
Log.d("cropImageUri", result.getUri().getPath());
new PostDataAsyncTask().execute();
Toast.makeText(this, "Photo Selected Successfully", Toast.LENGTH_LONG).show();
}
else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE)
{
Toast.makeText(this, "Photo Selection Failed", Toast.LENGTH_SHORT).show();
}
}
}
take permissions for
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
This solution will save your croped image to /storage/emulated/0/yourfolder/yourimage.jpg
I am capturing an image and store it in storage in mobile but when I get this image it cannot show any thing in Image View. I have tried a lot of code to get images from file but none of them are working in my emulator or real Samsung device.
enter code here
imageHolder = (ImageView)findViewById(R.id.captured_photo);
Button capturedImageButton = (Button)findViewById(R.id.photo_button);
capturedImageButton.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent photoCaptureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(photoCaptureIntent, requestCode);
}
});
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(this.requestCode == requestCode && resultCode == RESULT_OK){
Bitmap bitmap = (Bitmap)data.getExtras().get("data");
String partFilename = currentDateFormat();
storeCameraPhotoInSDCard(bitmap, partFilename);
// display the image from SD Card to ImageView Control
String storeFilename = "photo_" + partFilename + ".jpg";
Bitmap mBitmap = getImageFileFromSDCard(storeFilename);
imageHolder.setImageBitmap(mBitmap);
}
}
private String currentDateFormat(){
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_HH_mm_ss");
String currentTimeStamp = dateFormat.format(new Date());
return currentTimeStamp;
}
private void storeCameraPhotoInSDCard(Bitmap bitmap, String currentDate){
File outputFile = new File(Environment.getExternalStorageDirectory(), "photo_" + currentDate + ".jpg");
try {
FileOutputStream fileOutputStream = new FileOutputStream(outputFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream);
fileOutputStream.flush();
fileOutputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private Bitmap getImageFileFromSDCard(String filename){
/* Bitmap bitmap = null;
File imageFile = new File(Environment.getExternalStorageDirectory() + filename);
try {
FileInputStream fis = new FileInputStream(imageFile);
bitmap = BitmapFactory.decodeStream(fis);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return bitmap; */
File imageFile = new File(Environment.getExternalStorageDirectory() + filename);
// File imgFile = new File(filename);
//("/sdcard/Images/test_image.jpg");
Bitmap myBitmap;
if(imageFile.exists()){
myBitmap = BitmapFactory.decodeFile(imageFile.getAbsolutePath());
// ImageView myImage = (ImageView) findViewById(R.id.imageviewTest);
// myImage.setImageBitmap(myBitmap);
return myBitmap;
}
return null;
}
First of All make sure you have declared the "Access External Storage" and "Access Hardware Camera" permissions in "AndroidManifest" and if you are using Android version 23 or 23+ then you have to take permissions on run-time.
If this is not the problem then use this code given below, it's working fine for me.
For Camera:
Intent takePicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(takePicture, ACTION_REQUEST_CAMERA);
For Gallery:
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
Intent chooser = Intent.createChooser(intent, "Choose a Picture");
startActivityForResult(chooser, ACTION_REQUEST_GALLERY);
OnActivityResultMethod:
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
switch (requestCode) {
case ACTION_REQUEST_GALLERY:
Uri galleryImageUri = data.getData();
try{
Log.e("Image Path Gallery" , getPath(getActivity() , galleryImageUri));
selectedImagePath = getPath(getActivity() , galleryImageUri);
} catch (Exception ex){
ex.printStackTrace();
Log.e("Image Path Gallery" , galleryImageUri.getPath());
selectedImagePath = galleryImageUri.getPath();
}
break;
case ACTION_REQUEST_CAMERA:
// Uri cameraImageUri = initialURI;
Uri cameraImageUri = data.getData();
Log.e("Image Path Camera" , getPath(cameraImageUri));
selectedImagePath = getPath(cameraImageUri);
break;
}
}
}
Method to get path of Image returned from Camera:
/**
* helper to retrieve the path of an image URI
*/
public String getPath(Uri uri) {
// just some safety built in
if( uri == null ) {
// TODO perform some logging or show user feedback
return null;
}
// try to retrieve the image from the media store first
// this will only work for images selected from gallery
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = getActivity().managedQuery(uri, projection, null, null, null);
if( cursor != null ){
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
// this is our fallback here
return uri.getPath();
}
Good Day
I'm trying to make app that capture image and then display it in gridview
but i when i click the button to start capture this error appear.
Logcat:
java.lang.SecurityException: Permission Denial: starting Intent {
act=android.media.action.IMAGE_CAPTURE flg=0x3
cmp=com.android.camera2/com.android.camera.CaptureActivity
clip={text/uri-list
U:file:///storage/emulated/0/Pictures/MyInvoice/IMG_20160223_032401.jpg}
(has extras) } from ProcessRecord{8f9b88f
1356:com.example.labon.invoicemanger/u0a62} (pid=1356, uid=10062) with
revoked permission android.permission.CAMERA
at android.os.Parcel.readException(Parcel.java:1599)
My Code:
myLists = new ArrayList<Images>();
adapter = new ImageListAdapter(getActivity(), R.layout.img_list_view, myLists);
Button myButton = (Button) view.findViewById(R.id.camerabutton);
myButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
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
startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE); // start the image capture Intent
}
});
myGridView = (GridView) view.findViewById(R.id.gridView);
myGridView.setAdapter(adapter); /**
* Create a file Uri for saving an image or video
*/
public Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(type));
}
/**
* returning image /
*/
private static File getOutputMediaFile(int type) {
// External sdcard location
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), IMAGE_DIRECTORY_NAME);
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
mediaStorageDir.mkdirs();
// if (!mediaStorageDir.mkdirs()) {
Log.d(IMAGE_DIRECTORY_NAME, "Oops! Failed create "
+ IMAGE_DIRECTORY_NAME + " directory");
//return null;
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "IMG_" + timeStamp + ".jpg");
} else {
return null;
}
return mediaFile;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case 1:
if (resultCode == Activity.RESULT_OK) {
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getActivity().getContentResolver().query(selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
//file path of captured image
String filePath = cursor.getString(columnIndex);
//file path of captured image
File f = new File(filePath);
String filename = f.getName();
cursor.close();
//Convert file path into bitmap image using below line.
Bitmap yourSelectedImage = BitmapFactory.decodeFile(filePath);
//put bitmapimage in your imageview
ImageView imageView = (ImageView) view.findViewById(R.id.imageListView);
imageView.setImageBitmap(BitmapFactory.decodeByteArray(images.getImageBlob(), 0, images.getImageBlob().length));
//newImageView.setImageBitmap(yourSelectedImage); }
if (resultCode == getActivity().RESULT_CANCELED) {
// user cancelled Image capture
Toast.makeText(getActivity(), "User cancelled image capture", Toast.LENGTH_SHORT)
.show();
} else {
// failed to capture image
Toast.makeText(getActivity(), "Sorry! Failed to capture image", Toast.LENGTH_SHORT)
.show();
}
} }
Are you running this on marshmallow? Because if you are, the permission structure has changed. And you should read the documentation # http://developer.android.com/training/permissions/index.html .
The user must grant the permission explicitly.
you need to add user permission to androidmanifest.xml
<uses-permission android:name="android.permission.CAMERA" />
if you need to store the image to storage you have to add :
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
I'm trying to store a newly captured image through the Camera on my Storage and then display the image on an imageview. However, the image does not get stored.
My code:
private SurfaceView mSurfaceView;
private SurfaceHolder mSurfaceHolder;
private Camera mCamera;
......more code...
captureImage.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
mCamera.takePicture(null, null, new PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
File pictureFile;
pictureFile = new File(String.format("/sdcard/%d.jpg", System.currentTimeMillis()));
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
}
catch (Exception e) {
Log.d("ERR",e.toString());
}
//Display
Uri uri = Uri.fromFile(pictureFile);
imageViewer.setImageURI(uri);
}
});
}
});
Is my code correct for writing and displaying the image? I do not see any image on my storage and the imageview doesn't get populated by the image either. What am I doing wrong?
Create folder where you want to keep your photos.
Give full path name to create file .
//in this example MyImages is folder where you will keep your photos
File storageDir = new File(Environment.getExternalStorageDirectory() + "/", "MyImages");
if (!storageDir.exists()) {
storageDir.mkdirs();//directory created
}
// get the current timestamp
String timest = new SimpleDateFormat("yyyyMMdd_HHmmss")
.format(new Date());
//Create your picture file
File pictureFile;
pictureFile = new File(storageDir.getPath()+File.separator+ "IMG_" + timeStamp + ".jpg");
1- make sure you have what it takes Permissions
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
2- Create a directory on your mobile
public static void createDirectory(Context context) {
String directoryPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsolutePath() + "/YOURDIRECTORYNAME";
try {
File directory = new File(directoryPath);
if (!directory.exists()) {
directory.mkdirs();
}
} catch (Exception e) {
e.printStackTrace();
}
}
3- This method used to take the photo and create file.
private void takePictures() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getActivity().getPackageManager()) != null) {
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
}
if (photoFile != null) {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
}
4- Creates the file and save it in the folder.
private File createImageFile() throws IOException {
Calendar c = Calendar.getInstance();
SimpleDateFormat timeData = new SimpleDateFormat("dd-MMM-yyyy-HH:mm:ss");
//TODO declared global variables datePicture and imageFileName
datePicture = timeData.format(c.getTime());
imageFileName = Config.IMAGE_NAME_DEFOULT + datePicture;
File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES + "/YOURDIRECTORYNAME");
File image = File.createTempFile(imageFileName, ".png", storageDir);
Log.v("test_photo" ,image.getName());
//TODO declared global variables fileName and mCurrentPhotoPath
fileName = image.getName();
mCurrentPhotoPath = image.getAbsolutePath();
return image;
}
5- Get the picture reveal it in your imageView and save in your DB.
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_IMAGE_CAPTURE) {
if (resultCode == getActivity().RESULT_OK) {
//show directly
Bundle extras = data.getExtras();
Bitmap bitmap = extras.get("data");
youtImageView.setImageBitmap(bitmap);
/* here show in your imageView directly or
insert into database variables fileName and mCurrentPhotoPath
then you'll have to get it if you want to display from the DB */
} else if (resultCode == getActivity().RESULT_CANCELED) {
}
}
}
I hope it helps!
First, does your app's manifest contain the necessary permission to write to the SD card?
<manifest ...>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
...
</manifest>
and second, I'm not sure that you have the correct path to the SD card. The API docs suggest:
File sdPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
String filename = Long.toString(System.currentTimeMillis())+".jpg";
File pictureFile;
pictureFile = new File(sdPath, filename);
EDIT: To display the image using the URL, you could try:
FileInputStream inputStream = new FileInputStream(pictureFile);
Drawable d = Drawable.createFromStream(inputStream, pictureFile.getName());
imageViewer.setImageDrawable(d);