Cant see taken pictures after saving as file - android

I want to take a picture and save it as a file on the sd-card. All works fine, the camera starts, the pictures were taking, and saving. If i check the picturefolder on my device, i see the taken picute, but if i check the folder from another actvity, i cant see the taken pictures. The same, if i check the folder from my pc. What is wrong with my code?
Here is my code for the Cameraactivity
//Init ImageView
mPhotoCapturedImageView = (ImageView) findViewById(R.id.imgViewThumbNail);
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, ACTIVITY_START_CAMERA_APP);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == ACTIVITY_START_CAMERA_APP && resultCode == RESULT_OK) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
mPhotoCapturedImageView.setImageBitmap(thumbnail);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "IMAGE_" + timeStamp+ "_";
File file = new File(Environment.getExternalStorageDirectory()+ PHOTO_ALBUM + imageFileName + ".jpg");
try {
file.createNewFile();
FileOutputStream fo = new FileOutputStream(file);
//5
fo.write(bytes.toByteArray());
fo.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
The path of PHOTO_ALBUM is
public static final String PHOTO_ALBUM = "/MyIdea/IdeaGallery/";

I found out, that SD-Card is scanning after mounting and show all new pictures. This simply line of code solve all my problems:
MediaScannerConnection.scanFile(CameraActivity.this, new String[]{file.getPath()}, new String[]{"image/jpeg"}, null);
Thanks all for the help!

Related

Hide camera images from user gallery

Hi I am trying to make the images captured from my app inaccessible to the user. First I tried to save these images to internal storage which didnt work. Then I tried to hide them using "." infront of the folder name.I am not sure what the correct way to do this is. I also tried creating a file called .nomedia to bypass media scanner. I am very confused about the proper way to do this. Here's my code:
public String getImageUri(Context inContext, Bitmap inImage) {
/* *//* ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, ".title", null);
return Uri.parse(path);*//*
*/
File file = new File(Environment.getExternalStorageDirectory()
+ File.separator + "/.myFolder");
file.mkdirs();
File mFile = new File(Environment.getExternalStorageDirectory()
+ File.separator + "/.nomedia");
mFile.mkdirs();
FileOutputStream fOut = null;
try {
fOut = new FileOutputStream(file);
inImage.compress(Bitmap.CompressFormat.JPEG, 85, fOut);
fOut.flush();
fOut.close();
uri = MediaStore.Images.Media.insertImage(getContentResolver(), file.getAbsolutePath(), file.getName(), file.getName());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return uri;
}
If I use file.mkdirs() I get filenotfoundexception. If i remove that line I get no errors but my uri is empty.
Does the above function return the file path as well? I need the file path and the uri later on. Any help is appreciated.
I guess you don't have to add another extension or something else just save them in external cache dir of your app and gallery app won't able to read your private directory until unless you notify about them.
so store your camera images here and no gallery app can detect it.
context.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
sample code
public static File createPictureFile(Context context) throws IOException {
Locale locale = Locale.getDefault();
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", locale).format(new Date());
String fileName = "JPEG_" + timeStamp + "_";
// Store in normal camera directory
File storageDir = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
return File.createTempFile(fileName, ".jpg", storageDir);
}
Save your image to internal storage instead. Other applications like MediaScanner or Gallery do not have permission to read from your own application memory. Sample code:
private String saveToInternalStorage(Bitmap bitmapImage){
ContextWrapper cw = new ContextWrapper(getApplicationContext());
// path to /data/data/yourapp/app_data/imageDir
File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
// Create imageDir
File mypath=new File(directory,"profile.jpg");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(mypath);
// Use the compress method on the BitMap object to write image to the OutputStream
bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, fos);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return directory.getAbsolutePath();
}
Save the image with different extension.
For example: .jpg can be saved as .ttj.
Try this code. Set where you want to save the photo. Once you receive response on onActivityResult(), in the desired URI, you will get the photo.
public void captureImageFromCamera() {
fileUri = FileUtils.getInstance().getOutputMediaFile(null);
if(fileUri == null){
Utilities.displayToastMessage(ApplicationNekt.getContext(),
context.getString(R.string.unable_to_access_image));
return;
}
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(intent, TAKE_PICTURE);
}
Following function will give you desired path. Change it based on your project need.
public Uri getOutputMediaFile(String imageNameWithExtension) {
if (imageNameWithExtension == null)
imageNameWithExtension = "image_" + System.currentTimeMillis() + ".jpg";
String extPicDir = getExtDirPicturesPath();
if (!Utilities.isNullOrEmpty(extPicDir)) {
File mediaFile = new File(extPicDir, imageNameWithExtension);
return Uri.fromFile(mediaFile);
} else {
Log.d("tag", "getOutputMediaFile." +
"Empty external path received.");
return null;
}
}
public String getExtDirPicturesPath() {
File file = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
if (file != null)
return file.getPath();
else
Log.d("", "getExtDirPicturesPath failed. Storage state: "
+ Environment.getExternalStorageState());
return null;
}
To get the resultant photo.
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode != Activity.RESULT_OK)
return;
switch (requestCode) {
case TAKE_PICTURE:
//fileuri variable has the path to your image.
break;
}

Image directory not created when i take picture from my app

I am working in android studio. Building an app in which i am using a camera. When i run my app the app works fine. I capture the image it does captured the image. But the folder i created is not showing in my gallery. I am saving images in my local storage and not in SD CARD. I was very curious that why the folder is not created as it doesn't gives me any error so it should be in my gallery. So i restarted my device and after restarting i can see the folder in my gallery and the images taken in it. I again open the app and took images from it but again the images were not shown in the folder.
Below is my code in which i am making ta directory for saving images
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)
{
if(resultCode == Activity.RESULT_OK)
{
Bitmap bmp = (Bitmap)data.getExtras().get("data");
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] byteArray = stream.toByteArray();
// convert byte array to Bitmap
Bitmap bitmap = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
if(isStoragePermissionGranted())
{
SaveImage(bitmap);
}
}
}
private void SaveImage(Bitmap finalBitmap) {
String root = Environment.getExternalStorageDirectory().getAbsolutePath().toString();
Log.v(LOG_TAG, root);
File myDir = new File(root + "/captured_images");
myDir.mkdirs();
Random generator = new Random();
int n = 1000;
n = generator.nextInt(n);
String fname = "Image-" + n + ".jpg";
File file = new File(myDir,fname);
if (file.exists())file.delete();
try {
FileOutputStream out = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.JPEG,100,out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Below is the picture of my debugging
**Note: **
As i am using native camera so the pictures are saved in the camera roll folder i.e. the default folder in my device. But the image saved there is not the compressed one, the compress image should be saved in my created folder.
I am stuck to it and don't know what to do.
Any help would be highly appreciated.
You need to invoke scanFile(Context context, String[] paths, String[] mimeTypes, MediaScannerConnection.OnScanCompletedListener callback) method of MediaScannerConnection.
MediaScannerConnection provides a way for applications to pass a newly created or downloaded media file to the media scanner service. This will update your folder with the newly saved media.
private void SaveImage(Bitmap finalBitmap) {
//....
if(!storageDir.exists()){
storageDir.mkdirs();
}
//...
file.createNewFile();
try {
MediaScannerConnection.scanFile(context, new String[] {file.getPath()} , new String[]{"image/*"}, null);
FileOutputStream out = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.JPEG,100,out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
try this
private void saveBitmap(Bitmap bitmap) {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = timeStamp + ".jpg";
File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
final String fileLoc = storageDir.getAbsolutePath() + "/folderName/" + imageFileName;
File file = new File(fileLoc);
OutputStream os = null;
try {
os = new BufferedOutputStream(new FileOutputStream(file));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, os);
try {`enter code here`
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}

File copy from Gallery pick image to Internal Application Picture Directory Android

Getting image Content from Gallery picture
Now, I want to copy this image file(Which is picked from gallery) to my Internal App folder PICTURE directory(/storage/emulated/0/Android/data/MYApppackage/files/Pictures/).
I am creating new File in PICTURE Directory. file is created in internal AppDir / data / Pictures Directory and image with .JPG format but not showing image. Image is not visible. Image file is created with 0KB data.
I think its a file writing related issue or other i dont know.
Intent intent ;
if (Build.VERSION.SDK_INT < 19) {
intent = new Intent();
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
MainActivity.state = "AddBalance";
startActivityForResult(intent, REQUEST_GALLERY);
} else {
intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/*");
startActivityForResult(intent, REQUEST_GALLERY);
}
OnActivity Result of Gallery PickUp
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case REQUEST_GALLERY:
if (data != null) {
if (data != null) {
Bitmap bitmap=null;
uri1 = data.getData();
// showPhotoDialog(uri1);
try {
// bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), uri1);
InputStream image_stream = getActivity().getContentResolver().openInputStream(uri1);
bitmap= BitmapFactory.decodeStream(image_stream);
} catch (IOException e) {
e.printStackTrace();
}
Log.e(TAG,"Data URI----"+data.getData());
try {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "PNG_" + timeStamp + "_";
File storageDir = getActivity().getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, // prefix
".PNG", // suffix
storageDir // directory
);
// File imageFile= new File(storageDir,imageFileName);
FileOutputStream out;
try {
// out = getActivity().openFileOutput(image.getName(), Context.MODE_PRIVATE);
out = new FileOutputStream(image.getName());
/* ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] byteArray = stream.toByteArray();
out.write(byteArray);*/
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
out.close();
} catch (Exception e) {e.printStackTrace();}
// copyFile(new File(getRealPathFromURI(uri1)), image);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}`
}
Edit : Infos
getting value of uri1 from pickup gallery image : content://com.android.providers.media.documents/document/image%3A25877
I am Trying to write bitmap to File. Here is my Code. getBitmap from REQUEST_GALLERY and URI works fine . I am making File in Enviroment.PICTURE directory and write via OutPutStream. but Still File : PNG_54342323111.PNG
I also tried with ByteArrayOutputStream which you can see in comments but didnt works. also tried with OpenFileOutput but not working.

How can I save output image from camera directly to file without compression?

After compressing the file and then texting it, it recompresses again and is very choppy
I use Intent to bring up the camera. I get the result and bring up Intent to send as text.
private void takePic() {
Intent cameraIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, 2);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 2) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
File file = writebitmaptofilefirst("route_image",photo);
Uri uri = Uri.fromFile(file);
fileToDelete = file;
Intent sendIntent = new Intent(Intent.ACTION_SEND);
sendIntent.putExtra("address", "8001111222");
sendIntent.putExtra(Intent.EXTRA_STREAM, uri);
sendIntent.setType("image/jpg");
startActivityForResult(sendIntent,3);
}
else if (requestCode == 3){
if (fileToDelete.exists()) fileToDelete.delete();
}
}
public static File writebitmaptofilefirst(String filename, Bitmap source) {
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
File mFolder = new File(extStorageDirectory + "/temp_images");
if (!mFolder.exists()) {
mFolder.mkdir();
}
OutputStream outStream = null;
File file = new File(mFolder.getAbsolutePath(), filename + ".jpg");
if (file.exists()) {
file.delete();
file = new File(extStorageDirectory, filename + ".jpg");
Log.e("file exist", "" + file + ",Bitmap= " + filename);
}
try {
outStream = new FileOutputStream(file);
source.compress(Bitmap.CompressFormat.JPEG, 90, outStream);
outStream.flush();
outStream.close();
} catch (Exception e) {
e.printStackTrace();
}
Log.e("file", "" + file);
return file;
}
This works great except the resulting image texted is choppy. If I send the same pic that ends up in the Gallery it converts that down and the result is 100 times better at the receiving end. Can I save the Bitmap I get from the camera call directly without compression, the file will be deleted after the sending of the picture. The user actually takes the pic and then hits the send button on the default sms app.
To save an image directly without compressing use AndroidBmpUtil:
new AndroidBmpUtil().save(source, file);
Instead of
source.compress(Bitmap.CompressFormat.JPEG, 90, outStream);
use
source.compress(Bitmap.CompressFormat.PNG, 100, outStream);
JPEG is a lossy format hence the choppy result.

capture photo inside app with original resolution in android

I'm using camera intent to capture image inside my android app. After capturing I save pics into mobile internal/External storage in a specific folder. The problem is that these pics are not being saved in that resolution which camera has normally, their resolution is very low.
here is my code
Intent intent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, 0);
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
Bitmap bp = (Bitmap) data.getExtras().get("data");
/*********** Load Captured Image And Data Start ****************/
String extr = Environment.getExternalStorageDirectory().toString()
+ File.separator + "ScannerMini";
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
.format(new Date());
imageName = timeStamp + ".jpg";
if (Environment.MEDIA_MOUNTED.equals(state)) {
// We can read and write the media
myPath = new File(getExternalFilesDir(filepath), imageName);
//File myPath = new File(extr, imageName);
}
else{
myPath = new File(extr, imageName);
}
FileOutputStream fos = null;
try {
fos = new FileOutputStream(myPath);
bp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
MediaStore.Images.Media.insertImage(getApplicationContext()
.getContentResolver(), bp, myPath.getPath(), imageName);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
can anybody tell me that what should i do to save image in original resolution. Any help would be much appreciated. Thank You :)
Bitmap bp = (Bitmap) data.getExtras().get("data");
By doing this you will only get a thumbnail image. You need to specify MediaStore.EXTRA_OUTPUT option in your capture intent. This is a path where captured image will be stored. Refer to android docs Taking Photos Simply

Categories

Resources