I am using Camera from Android in my application ...... my requirement is , I am capturing live picture and saving it on a location decided by me not in a Camera folder from Gallery.
And then fetching photos with the help of Uri and displaying it in my application.
But what I have implemented is running properly on some device and on some devices my code couldn't able to create folder and captured image .... so I get nothing when my application wants to display photos.
I have tried my app on Galaxy S and Galaxy SII .... On galaxy S its not working properly, and strange thing is on some SII devices its working properly but some fails to create image and folder on specified location. But on Galaxy Tab everything is working fine.
Also I have tested it on Nexus S .... here problem is something different, on Nexus S when I start camera and capture an image, after that I can see image preview and there I have 2 option to save,cancel or retake .... but when I ask to save nothing happens and when I cancel it frees Camera, and for retake its working as it designed.
I dont understand why there is different findings on different devices .... even devices are from same manufacturer (like Galaxy SII)
I am posting my code ... if someone has hint please share it with me... Thank you.
public static String EXTERNAL_STORAGE_PATH = Environment.getExternalStorageDirectory().getAbsolutePath().toString()+"/DCIM/";
private String imagePath = ImageDecoder.EXTERNAL_STORAGE_PATH;
imagePath = imagePath + projectdata.getProjectName().toString().trim() + "/"
+ System.currentTimeMillis() + ".jpg";
File imageFile = new File(imagePath);
Uri imageFileUri = Uri.fromFile(imageFile);
Intent captureImage = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
captureImage.putExtra(MediaStore.EXTRA_OUTPUT, imageFileUri);
startActivityForResult(captureImage, CAMERA_PIC_REQUEST);
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
String imgDescription = null;
switch (requestCode) {
case CAMERA_PIC_REQUEST:
if (resultCode == RESULT_OK) {
cam = new Controller_Camera(context, sessiondata, projectdata);
imgDescription = getString(R.string.DEFAULT_IMAGE_TITLE) + DateTimeUtility.GetSystemDate();
String response = cam.savePhotoWithIssue(imagePath, app, imgDescription,
getString(R.string.DEFAULT_ISSUE_NAME), getString(R.string.DEFAULT_IMAGE_TITLE));
if (response == "Successfull") {
Intent issueeditor = new Intent(context, IssueEditor.class);
issueeditor.putExtra("TODO", "editissue");
issueeditor.putExtra("TAB", "Photos");
issueeditor.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
finish();
startActivity(issueeditor);
} else {
Toast.makeText(context, getResources().getString(R.string.FAILURE_SAVING), Toast.LENGTH_SHORT)
.show();
}
}
break;
Just check whether SD card is mounted or not
private boolean isSDCARDMounted() {
String status = Environment.getExternalStorageState();
if (status.equals(Environment.MEDIA_MOUNTED))
return true;
return false;
}
if (isSDCARDMounted()) {
File f = new File(Environment.getExternalStorageDirectory(),
TEMP_PHOTO_FILE);
try {
f.createNewFile();
} catch (IOException e) {
}
return f;
}
Related
I am trying to use default camera with Intent for both image and video capture.
when i turn to front camera and capture the image or video preview (captured image or video ) is inverted . So now I want to put preScale in frontCamera. But didn't know where to find Camera ID in default Camera.!!
Note : this is not Custom Camera.!!
Problem is : Captured Image from Front camera getting image is mirror image. Look into it if there any problem ? I didnt get ! Thx
Even stored captured image in SDCard also mirror image! Now how to preScale or any other idea to correct iT??
Help!
photo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
captureImage();
}
});
CatureImage method
private void captureImage() {
Context context = this;
PackageManager packageManager = context.getPackageManager();
if (packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA) == false
&& packageManager
.hasSystemFeature(PackageManager.FEATURE_CAMERA_ANY) == false) {
Toast.makeText(CameraRolling2.this, "camera not available'",
Toast.LENGTH_SHORT).show();
return;
}
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent
.resolveActivity(CameraRolling2.this.getPackageManager()) != null) {
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
Toast.makeText(CameraRolling2.this, "Error connecting camera",
Toast.LENGTH_SHORT).show();
ex.printStackTrace();
}
// Continue only if the File was successfully created
if (photoFile != null) {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photoFile));
startActivityForResult(takePictureIntent,
CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
showImg.setImageBitmap(null);
}
}
}
#SuppressLint("SimpleDateFormat")
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, ".jpg", storageDir);
mCurrentPhotoPath = image.getAbsolutePath();
Log.v("createImageFile", "" + mCurrentPhotoPath);
return image;
}
and My Activity Result
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE
&& resultCode == Activity.RESULT_OK) {
File imgFile = new File(mCurrentPhotoPath);
if (imgFile.exists()) {
BitmapFactory.Options bitmap_options = new BitmapFactory.Options();
bitmap_options.inSampleSize = 4;
bitmap_options.outHeight = 200;
bitmap_options.outWidth = 200;
Bitmap myBitmap = BitmapFactory.decodeFile(
imgFile.getAbsolutePath(), bitmap_options);
showImg.setImageBitmap(myBitmap);
if (showImg.getDrawable() == null) {
Log.e("IMAGEVIEW", "NULL IMAGE");
imageflag = false;
} else {
Log.e("IMAGEVIEW", "IMAGE VIEW UPDATED");
imageflag = true;
}
}
}
if (resultCode == Activity.RESULT_CANCELED) {
Toast.makeText(CameraRolling2.this, "Camera option canceled",
Toast.LENGTH_SHORT).show();
imageflag = false;
}
I am trying to use default camera with Intent for both image and video capture
There is no single "default camera with Intent" in Android. There are thousands of Android device models. These ship with hundreds of different "default camera with Intent" apps. Users can install other "default camera with Intent" apps from the Play Store or other places. Any one of those apps could be what the user chooses to use to take the picture (ACTION_IMAGE_CAPTURE) or record the video (ACTION_VIDEO_CAPTURE).
when i turn to front camera and capture the image or video preview (captured image or video ) is inverted
I am going to guess that by "inverted", you mean "rotated".
There are hundreds of different possible camera apps. Many will save the image or video with metadata that tells the viewer app to rotate the image (e.g., JPEG photos might have an orientation EXIF header). Some will not, electing to rotate the content themselves.
Also, the images or videos from any camera (front-facing, rear-facing, external) could be rotated.
Hence, you should not be assuming that the rotation is tied to the particular camera that the user used. Instead, examine the actual content and react accordingly. This sample project demonstrates this for rotating a JPEG image, using a couple of different techniques.
So now I want to put preScale in frontCamera.
You cannot control this.
But didn't know where to find Camera ID in default Camera.!!
You cannot control this.
I'm trying to have an Intent that allows user to pick a photo or a video from the phone, then post the image to a server.
Here is how I do it :
public void lookForMedia(View v) {
KeyboardHelper.hideKeyboard(this, postContentEtx);
Intent myIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI);
myIntent.setType("image/*,video/*");
myIntent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(myIntent, MEDIA_GALLERY);
}
Then :
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case MEDIA_GALLERY:
if (resultCode == RESULT_OK) {
if (requestCode == PICTURE_SELECTED) {
mediaUri = data.getData();
ContentResolver cR = NewPostActivity.this.getContentResolver();
if (mediaUri == null) {
Toast.makeText(NewPostActivity.this, "Error while retrieving the media", Toast.LENGTH_LONG).show();
return;
}
String type = cR.getType(mediaUri);
if (type.startsWith("image")) {
mediaThumbnailImv.setImageURI(mediaUri);
videoUri = null;
thumbnailUri = null;
mediaRll.setVisibility(View.VISIBLE);
mediaThumbnailImv.setVisibility(View.VISIBLE);
mediaThumbnailNetworkImv.setVisibility(View.GONE);
} else if (type.startsWith("video")) {
videoUri = mediaUri;
mediaUri = null;
Bitmap videoThumbnail = ThumbnailUtils.createVideoThumbnail(FileUtil.getRealPathFromURI(NewPostActivity.this, videoUri), MediaStore.Images.Thumbnails.MINI_KIND);
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
FileOutputStream out = null;
try {
String filename = "thumb_" + timeStamp + "kfkb.png";
out = new FileOutputStream(NewPostActivity.this.getFilesDir() + filename);
videoThumbnail.compress(Bitmap.CompressFormat.PNG, 90, out);
thumbnailUri = Uri.fromFile(new File(NewPostActivity.this.getFilesDir() + filename));
mediaThumbnailImv.setImageURI(thumbnailUri);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
out.close();
} catch (Throwable ignore) {
}
}
mediaRll.setVisibility(View.VISIBLE);
mediaThumbnailImv.setVisibility(View.VISIBLE);
mediaThumbnailNetworkImv.setVisibility(View.GONE);
} else {
Toast.makeText(NewPostActivity.this, "Invalid media", Toast.LENGTH_LONG).show();
return;
}
}
}
break;
}
}
It works fine on the devices I tried (Nexus 5, LG G3, Samsung Galaxy S3, Wiko Cink Five), but some users told me that they couldn't see their photos or videos when clicking on the button (it seems that it occurs on older version of Android, but I cannot have more precise information right now). Is there a different way to do this, and to be sure that it works on most devices ? Is there something that I am doing wrong ?
First of all i think you doesn't understand correct that is the cross-platform.
Cross-Platform - is the independent from OS code that will be executed equally on each OS. For each OS - will be compiled executable file. For Android - apk. For Windows - exe. etc...
To your problem. If the users complained about incorrect logic working i recommend to you several things :
Log your stack trace with device_info into dump file to sdcard. And ask the user before application end - send this log to your email. Or something like this.
Try to find alternative way for picking image. For the worst case - write your own activity and scan system for images.
I'm getting pictures with the next code:
public void foto(View v) {
nom_foto = Environment.getExternalStorageDirectory()+ aptr.ruta_temp + cuadrilla + "/" + medidor + "_"+ cont_foto + ".jpg";
File arch = new File(Environment.getExternalStorageDirectory()+ aptr.ruta_temp+ cuadrilla);
if (!arch.exists())
arch.mkdirs();
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
int code = TAKE_PICTURE;
Uri output = Uri.fromFile(new File(nom_foto));
intent.putExtra(MediaStore.EXTRA_OUTPUT, output);
startActivityForResult(intent, code);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == TAKE_PICTURE) {
ImageView iv = (ImageView) findViewById(R.id.minifoto);
if (resultCode == RESULT_OK) {
new MediaScannerConnectionClient() {
private MediaScannerConnection msc = null;
{
msc = new MediaScannerConnection(getApplicationContext(), this);
msc.connect();
}
public void onMediaScannerConnected() {msc.scanFile(nom_foto,null);
}
public void onScanCompleted(String path, Uri uri)
{ msc.disconnect();}};
Toast.makeText(usuario_lectura.this,"Foto N° " + cont_foto + " agregada correctamente", Toast.LENGTH_LONG).show();
cont_foto++;
iv.setVisibility(View.VISIBLE);
iv.setImageBitmap(BitmapFactory.decodeFile(nom_foto));
}
}
if (resultCode == RESULT_CANCELED) {
File file = new File(nom_foto);
if (file.exists())
file.delete();
}
}
}
Everything works properly, the picture has taken correctly and saved on the SD card... But, I have to add a watermarker, including the date... How can I add it?, the camera activity doesn't give me these option...
In order to add a textual or graphical watermark to your image from the camera, you must open the image, edit it in a Canvas with Paint/Graphics overlays, then re-encode it as a .jpg image, and re-save it as a file on the SD card. You can save over the original file from the camera. All of these steps are fairly straightforward.
There is, however, a serious hurdle.
Most devices will not be able to open the full-size image from the camera in a single Bitmap. There is not enough heap memory available. Therefore, you will have to use a scale factor inSampleSize to open your image. Thus, the watermarked image will be forever smaller by some factor than the original from the camera.
I do not think there is any way around this issue :(
Hope someone may give some pointers (or an out right answer)...
Simple app, take an image using the built-in camera app, save the image to a separate application. Be done.
Problem: The camera application saves the image in the default app location (/mnt/sdcard/external_sd/DCIM/Camera) as well as my custom path (in code below).
Both files are exactly the same except for the file name. The external_sd file (the one I want gone) is saved with dashes (-) vs my custom file path saved with underscores. File sizes are exactly the same.
How can I stop this double image issue?
Is there an extra intent option I'm missing?
Or am I doing this completely wrong, missing something?
I'm using a Galaxy S Vibrant.
Code snippet:
private static Uri _outputFileUri;
private static File _file;
private ImageView _image;
private SimpleDateFormat _simpleDateFormat = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss");
_takePicture = (Button) findViewById(R.id.takePicture);
_takePicture.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
_intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
_file = new File(Environment.getExternalStorageDirectory() +
"/Android/data/my own folder/files/",
_simpleDateFormat.format(new Date()).toString() +
".jpg");
_outputFileUri = Uri.fromFile(_file);
_intent.putExtra(MediaStore.EXTRA_OUTPUT, _outputFileUri);
startActivityForResult(_intent, CAMERA_ACTIVITY);
}
});
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_CANCELED) {
Toast.makeText(this, "Activity cancelled", Toast.LENGTH_LONG).show();
return;
}
switch (requestCode) {
case CAMERA_ACTIVITY:
if (resultCode == RESULT_OK) {
try{
Bitmap b = MediaStore.Images.Media.getBitmap(getContentResolver(), _outputFileUri);
_image.setImageBitmap(b);
_image.invalidate();
}
catch(Exception e){
e.printStackTrace();
}
}
break;
}
}
This is device-dependent behavior. My observation is that HTC devices do not have this duplication problem, but Samsung devices do.
Please remove the following lines:
_file = new File(Environment.getExternalStorageDirectory() +
"/Android/data/my own folder/files/",
_simpleDateFormat.format(new Date()).toString() +
".jpg");
_outputFileUri = Uri.fromFile(_file);
_intent.putExtra(MediaStore.EXTRA_OUTPUT, _outputFileUri);
Also update the code to get the image from intent:
Bitmap b = (Bitmap) data.getExtras().get("data");
_image.setImageBitmap(b);
_image.invalidate();
This way picture wouldn't be saved on sd card or default location.
I had the same problem and gave up. Sometime later I found out that I was not getting it anymore and I'm not sure what change I made to my code, but I think that it was MediaStore's fault (check my unsolved question: Weird camera Intent behavior)
As you already have the image URI, why don't you use it to set the ImageViews' bitmap?
// void setImageURI(Uri uri)
_image.setImageBitmap(_outputFileUri);
I had this issue and here is how i solved it :
File createImageFile() throws IOException{
String timestamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String filename = "IMG_"+timestamp+"_";
File image = File.createTempFile(filename,".jpg",mGalleryFolder );
if (image.length() == 0 ){
boolean delete = image.delete();
}
mLocation = image.getAbsolutePath();
return image;
}
It's not exactly solving but works for me ;)
I've got a problem in saving a picture in a full size after capturing it using ACTION_IMAGE_CAPTURE intent the picture become very small , its resolution is 27X44 I'm using 1.5 android emulator, this is the code and I will appreciate any help:
myImageButton02.setOnClickListener
(
new OnClickListener()
{
#Override
public void onClick(View v)
{
// create camera intent
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//Grant permission to the camera activity to write the photo.
intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
//saving if there is EXTRA_OUTPUT
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File
(Environment.getExternalStorageDirectory(), "testExtra" + String.valueOf
(System.currentTimeMillis()) + ".jpg")));
// start the camera intent and return the image
startActivityForResult(intent,1);
}
}
);
#Override
protected void onActivityResult (int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
// if Activity was canceled, display a Toast message
if (resultCode == RESULT_CANCELED)
{
Toast toast = Toast.makeText(this,"camera cancelled", 10000);
toast.show();
return;
}
// lets check if we are really dealing with a picture
if (requestCode == 1 && resultCode == RESULT_OK)
{
String timestamp = Long.toString(System.currentTimeMillis());
// get the picture
Bitmap mPicture = (Bitmap) data.getExtras().get("data");
// save image to gallery
MediaStore.Images.Media.insertImage(getContentResolver(), mPicture, timestamp, timestamp);
}
}
}
Look at what you are doing:
you specify a path where your just taken picture is stored with intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File (Environment.getExternalStorageDirectory(), "testExtra" + String.valueOf (System.currentTimeMillis()) + ".jpg")));
when you access the picture you 'drag' the data out of the intent with Bitmap mPicture = (Bitmap) data.getExtras().get("data");
Obviously, you don't access the picture from its file. As far as I know Intents are not designed to carry a large amount of data since they are passed between e.g. Activities. What you should do is open the picture from the file created by the camera intent. Looks like that:
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
// Limit the filesize since 5MP pictures will kill you RAM
bitmapOptions.inSampleSize = 6;
imgBitmap = BitmapFactory.decodeFile(pathToPicture, bitmapOptions);
That should do the trick. It used to work for me this way but I am experiencing problems since 2.1 on several devices. Works (still) fine on Nexus One.
Take a look at MediaStore.ACTION_IMAGE_CAPTURE.
Hope this helps.
Regards,
Steff