android camera saving, but not showing up on the sd card - android

I am working on adding a camera to my application, I have basically decided to go with adding an intent to it, and using the built in camera. The intent works, it calls it just fine, but when it goes to save it gets weird. according to Eclipse the photos are saving to the SD card, I can see them and pull them off when i go under FileExplorer. However, when I actually go to and explore the SD card, the files are not there.
public class C4Main extends Activity {
private static final int REQUEST_CODE = 1;
private Bitmap bitmap;
private ImageView imageView;
private Camera cam;
private SurfaceHolder sh;
private Uri fileUri;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Log.d("testing","before intent");
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(1); // create a file to save the image
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file name
Log.d("testing","fileUri: "+fileUri);
// start the image capture Intent
startActivityForResult(intent, 100);
Log.d("testing","after startactivity");
}
private static Uri getOutputMediaFileUri(int type){
return Uri.fromFile(getOutputMediaFile(type));
}
/** Create a File for saving an image or video */
private static File getOutputMediaFile(int type){
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "MyCameraApp");
// This location works best if you want the created images to be shared
// between applications and persist after your app has been uninstalled.
// Create the storage directory if it does not exist
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
Log.d("MyCameraApp", "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile;
if (type == 1){
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"IMG_"+ timeStamp + ".jpg");
Log.d("testing loop","Filepath: "+mediaFile.getPath());
} else if(type == 2) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"VID_"+ timeStamp + ".mp4");
} else {
return null;
}
return mediaFile;
}
}
that is the code that I am using, copied from developer.google. And as I said according to FileExplorer in Eclipse it is saving to the designated path, but it just is not on my SD card. My hardware is ASUS Transformer prime running android 4.0.3.
Tha manifest is set-up with permission for both external writing and camera use.
Any help would be greatly appreciated.

I'm using this intent for using built-in camera. It automatically stores the image in SD card.
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
flagImage=1;
startActivityForResult(cameraIntent, CAMERA_REQUEST);

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
try {
if (requestCode == CAMERA_REQUEST) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
Cursor c1 = cr.query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, p1, null,
null, p1[1] + " DESC");
if (c1.moveToFirst()) {
String uristringpic = "content://media/external/images/media/"
+ c1.getInt(0);
Uri newuri = Uri.parse(uristringpic);
// Log.i("TAG", "newuri "+newuri);
String snapName = getRealPathFromURI(newuri);
Uri u = Uri.parse(snapName);
File f = new File("" + u);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
photo.compress(CompressFormat.PNG, 0 /* ignored for PNG */,
bos);
byte[] bitmapdata = bos.toByteArray();
// Storing Image in new folder
StoreByteImage(mContext, bitmapdata, 100, fileName);

Related

Trying to take a picture and then store it + have access to it

So, I have an app where I want to take a picture, store it to internal storage, and then be able to retrieve it later (presumably via its Uri). Here is what I have thus far:
This code is triggered when my custom camera button is pressed.
cameraButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Intent takePic = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File file = herp(MEDIA_TYPE_IMAGE);
if (file != null) {
fileUri = getOutputMediaFileUri(file);
Log.d("AddRecipeActivity", fileUri.toString());
takePic.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(takePic, CAMERA_REQUEST);
}
}
});
Next, I've defined two methods later on in the code(mostly taken from the android developer site):
/** Create a file Uri for saving an image or video */
private static Uri getOutputMediaFileUri(File file){
return Uri.fromFile(file);
}
/** Create a File for saving an image or video */
public File herp(int type){
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
Boolean a = false;
String externalDirectory= getFilesDir().getAbsolutePath();
File folder= new File(externalDirectory + "/NewFolder");
// This location works best if you want the created images to be shared
// between applications and persist after your app has been uninstalled.
// Create the storage directory if it does not exist
if (!folder.exists()){
a = folder.mkdirs();
Log.d("AddRecipeActivity", String.valueOf(a));
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE){
mediaFile = new File(folder.getPath() + File.separator +
"IMG_"+ timeStamp + ".jpg");
} else {
return null;
}
if(mediaFile == null){
Log.d("AddRecipeActivity", "Media file is null");
}
return mediaFile;
}
When I print my Uri (right before triggering the intent) I get the following output.
04-04 04:22:40.757 22402-22402/scissorkick.com.project2 D/AddRecipeActivity: file:///data/user/0/scissorkick.com.project2/files/NewFolder/IMG_20160404_042240.jpg
Also, when I check if the directory is made, the boolean is true.
When my camera intent's onActivityResult is run, however, the result code is 0.
Why might it fail at this point? I've defined the appropriate permissions in the manifest, and also request external storage write permissions during run time.
Edit: Added the onActivityResult:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data){
if(requestCode == CAMERA_REQUEST){
Log.d("AddRecipe", String.valueOf(resultCode));
if(resultCode == RESULT_OK){
photo = (Bitmap) data.getExtras().get("data");
thumb = ThumbnailUtils.extractThumbnail(photo, 240, 240);
photoView.setImageBitmap(thumb);
//Toast.makeText(getApplicationContext(), "image saved to:\n" + data.getData(), Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(getApplicationContext(), "Fail", Toast.LENGTH_SHORT).show();
}
}
}
There's some nonsense code in the onActivityResult, but the point is that the resultCode = 0 and I don't know why.
In your final activity, put the below code
data.putExtra("uri", uri);//uri = your image uri
getActivity().setResult(""result_code", data);
getActivity().finish();
Then in your onActivityResult code you can get the uri like
Uri uri = data.getExtras().getParcelable("uri");
Then you can use this Uri value to retrieve your image.
There is how i take picture in my app!
When i press my own Image Button
static final int REQUEST_IMAGE_CAPTURE = 1;
static final int REQUEST_TAKE_PHOTO = 1
static final String STATE_PHOTO_PATH = "photoPath";
ImageButton photoButton = (ImageButton) this.findViewById(R.id.take_picture_button);
photoButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dispatchTakePictureIntent();
}
});
And here how manage and create/store the file with image
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 = 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();
return image;
}
//Create a new empty file for the photo, and with intent call the camera
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(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException e) {
// Error occurred while creating the File
Log.e("Error creating File", String.valueOf(e.getMessage()));
}
// Continue only if the File was successfully created
if (photoFile != null) {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photoFile));
//I have the file so now call the Camera
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
}
}
private void openImageReader(String imagePath) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
Uri imgUri = Uri.parse(imagePath);
intent.setDataAndType(imgUri, "image/*");
startActivity(intent);
}
In the ActivityResult i only save a record in DB, with the Path of the image so i can retrieve it back and read the photo stored like file.
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
//Save the path of image in the DB
db.addCompito(new Compiti(activity_name, null, mCurrentPhotoPath));
refreshListView();
}
}
If you have some screen rotation don't forget to add something like
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save the user's current game state
savedInstanceState.putString(STATE_PHOTO_PATH, mCurrentPhotoPath);
// Always call the superclass so it can save the view hierarchy state
super.onSaveInstanceState(savedInstanceState);
}
public void onRestoreInstanceState(Bundle savedInstanceState) {
// Always call the superclass so it can restore the view hierarchy
super.onRestoreInstanceState(savedInstanceState);
// Restore state members from saved instance
mCurrentPhotoPath = savedInstanceState.getString(STATE_PHOTO_PATH);
}
WHY?
Because when the rotation change you can lose the file that you have created for the "new photo" and when you accept it and save it, your photopath is null and no image is created.

How to set the size and quality of a picture taken with the android camera?

I wrote this code that takes a picture with the camera then converts it to a jpeg file and uploads it to Parse.com as a ParseFile.
The problem is that the picture is really small (153 x 204 px) and really low quality.
I need the picture to be at least 5 MP quality and to crop it to 300x300 px.
Here is the code I use til now.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_picture);
img = (ImageView) findViewById(R.id.imgV);
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
byte[] image_byte_array;
ParseObject post_object = new ParseObject("Gallery");
Bundle extras = data.getExtras();
Bitmap image = (Bitmap) extras.get("data");
ByteArrayOutputStream stream = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 100, stream);
image_byte_array = stream.toByteArray();
ParseFile picture_file = new ParseFile("Picture.jpg", image_byte_array);
picture_file.saveInBackground();
post_object.put("photo", picture_file);
post_object.saveInBackground();
}
Thanks in advance.
Check this answer here.
A camera intent return a thumbnail by default, so you need to
fetch the full image.
Derek's solution is right, but you have to improve it.
the real juice lies in fetching the full image which happens here -
thumbnail = MediaStore.Images.Media.getBitmap(
getContentResolver(), imageUri);
imgView.setImageBitmap(thumbnail);
imageurl = getRealPathFromURI(imageUri);
full path will be given by getRealPathFromURI().
Check the link below
http://developer.android.com/guide/topics/media/camera.html#intent-image
You have to add a Uri which is the Uri of file to store the photo
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file name
a full sample
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_picture);
img = (ImageView) findViewById(R.id.imgV);
// 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);
}
/** Create a file Uri for saving an image or video */
private static Uri getOutputMediaFileUri(int type){
return Uri.fromFile(getOutputMediaFile(type));
}
/** Create a File for saving an image or video */
private static File getOutputMediaFile(int type){
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "MyCameraApp");
// This location works best if you want the created images to be shared
// between applications and persist after your app has been uninstalled.
// Create the storage directory if it does not exist
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
Log.d("MyCameraApp", "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE){
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"IMG_"+ timeStamp + ".jpg");
} else if(type == MEDIA_TYPE_VIDEO) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"VID_"+ timeStamp + ".mp4");
} else {
return null;
}
return mediaFile;
}

Android Camera App (picture only shows up after reboot)

I'm having trouble with my camera app. I'm trying to make it snap a picture and then save it to a folder of the android device and it seems to be doing that, but the pictures only show up after I reboot the device. Furthermore, I seem to always end up with the result code of 0, so I never get to update my imageView. Why do I always get that result code?
/** Create a file Uri for saving an image */
private static Uri getOutputMediaFileUri(){
return Uri.fromFile(getOutputMediaFile());
}
/** Create a File for saving an image */
private static File getOutputMediaFile(){
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "myAppPics");
// Create the storage directory if it does not exist
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
Log.d("myAppPics", "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"IMG_"+ timeStamp + ".jpg");
return mediaFile;
}
/** Opening App*/
public void open(){
intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE_SECURE);
fileUri = getOutputMediaFileUri(); // create a file to save the image
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file name
startActivityForResult(intent, 0);
}
#Override
/**when you get the activity result*/
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
//if you want to keep the picture
if (resultCode == RESULT_OK )
{
//grab image data
Bundle extras = data.getExtras();
Bitmap bp = (Bitmap) extras.get("data");
//make imageView hold that image now
myImgV.setImageBitmap(bp);
Log.d("MyCameraApp", "update image");
}
//else just goes back to previously chosen image
else
Log.d("MyCameraApp", "don't want to update image "+resultCode);
}
To see the picture taken refresh the gallery using
refreshGallery(String fileUrl, Context ctx) {
Intent mediaScanIntent = new Intent(
Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(fileUrl);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
ctx.sendBroadcast(mediaScanIntent);
}

How to pass the captured image to a different activity to set to the image view in android and store in a databse

Can anybody tell how to pass the captured image to a different activity to set the image view in android and store in a database? Can anybody provide code?
Thanks
Try this...
1.Capture and get the bitmap of the captured image in the onActivityResult()
public void capture(View view) {
Intent cameraIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAPTURE_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == CAPTURE_REQUEST) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
}
}
}
2 Send the Image to the next Activity...You can send the Bitmap because it implements Parcelable
private void sendImage() {
Intent intent = new Intent(MainActivity.this, NextActivity.class);
intent.putExtra("image", thumbnail);
startActivity(intent);
}
3 Get the image in the NextActivity
Bundle extras = getIntent().getExtras();
if (extras != null) {
Bitmap image = (Bitmap) extras.get("image");
if (image != null) {
imageView.setImageBitmap(image);
}
}
you need to follow these steps :-
capture image using camera
save this image
get the file URI
In your next activity you can show this image using that file URI
let me know if you have any issue.
To Save your bitmap in sdcard use the following code
Store Image
private void storeImage(Bitmap image) {
File pictureFile = getOutputMediaFile();
if (pictureFile == null) {
Log.d(TAG,
"Error creating media file, check storage permissions: ");// e.getMessage());
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
image.compress(Bitmap.CompressFormat.PNG, 90, fos);
fos.close();
} catch (FileNotFoundException e) {
Log.d(TAG, "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d(TAG, "Error accessing file: " + e.getMessage());
}
}
To Get the Path for Image Storage
/** Create a File for saving an image or video */
private File getOutputMediaFile(){
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
File mediaStorageDir = new File(Environment.getExternalStorageDirectory()
+ "/Android/data/"
+ getApplicationContext().getPackageName()
+ "/Files");
// This location works best if you want the created images to be shared
// between applications and persist after your app has been uninstalled.
// Create the storage directory if it does not exist
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("ddMMyyyy_HHmm").format(new Date());
File mediaFile;
String mImageName="MI_"+ timeStamp +".jpg";
mediaFile = new File(mediaStorageDir.getPath() + File.separator + mImageName);
return mediaFile;
}

getoutputmediafileuri method is not accessible?

I'm learning how to take a picture and save it's path into a file.
According to the tutorials offers on android developers website, the method
getoutputmediafileuri() is used, however, when I tried to use that method, i found that it's
not accessible or undefined, i mean eclipse underlines this method with redline. I don't know
how to fix this error.
Please find below the code
public class SaveCameraImageDemoActivity extends Activity {
/** Called when the activity is first created. */
Button btn01;
private Uri fileURI;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn01 = (Button) findViewById(R.id.btn01);
btn01.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intenet = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileURI = getoutputmediafileuri();
//intenet.putExtra("output", uri.getPath());
startActivityForResult(intenet,0);
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
}
}
There is no inbuilt method getoutputmediafileuri() in android.
It is a custom method someone write for getting file URI to store captured images in particular directory. You have to defined and put logic for it. Instead of that use this code,
EDIT:
btn01.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent imageIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File imagesFolder = new File(Environment.getExternalStorageDirectory(), "MyImages");
imagesFolder.mkdirs(); // <----
File image = new File(imagesFolder, "image_001.jpg");
Uri uriSavedImage = Uri.fromFile(image);
imageIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
startActivityForResult(imageIntent,0);
}
});
Now this will store your camera captured images in MyImages directory in sdcard with image_001.jpg name.
The getoutputmediafileuri() method is defined here: http://developer.android.com/guide/topics/media/camera.html#saving-media
Now the document has added the code. Just paste the at the end of your Class, it work well for me. Code See As Below.
public static final int MEDIA_TYPE_IMAGE = 1;
public static final int MEDIA_TYPE_VIDEO = 2;
/** Create a file Uri for saving an image or video */
private static Uri getOutputMediaFileUri(int type){
return Uri.fromFile(getOutputMediaFile(type));
}
/** Create a File for saving an image or video */
private static File getOutputMediaFile(int type){
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "MyCameraApp");
// This location works best if you want the created images to be shared
// between applications and persist after your app has been uninstalled.
// Create the storage directory if it does not exist
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
Log.d("MyCameraApp", "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE){
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"IMG_"+ timeStamp + ".jpg");
} else if(type == MEDIA_TYPE_VIDEO) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"VID_"+ timeStamp + ".mp4");
} else {
return null;
}
return mediaFile;
}

Categories

Resources