Changing the path of photos clicked by camera intent - android

I my developing an app that clicks the photos and it should store the photos in a different folder than the default storage location. please guide me about it.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// 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);
}
This is the basic code, please tell me the changes needed to make in it.

You cannot change default folder location, but you can make copy of image for your use. If you want to change it, then play with system camera.
You Need to call on activity result and get captured image and store it on any location.
For my case file(image) name is currenttimestamp.jpg
#Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if (resultCode == RESULT_OK){
try {
AssetFileDescriptor videoAsset = getContentResolver().openAssetFileDescriptor(intent.getData(), "r");
FileInputStream fis = videoAsset.createInputStream();
File tmpFile = new File(Environment.getExternalStorageDirectory(), System.currentTimeMillis()+".jpg");
FileOutputStream fos = new FileOutputStream(tmpFile);
byte[] buf = new byte[1024];
int len;
while ((len = fis.read(buf)) > 0) {
fos.write(buf, 0, len);
}
EDIT
tell android you have copied the picture. This will make the folder show up as a gallery on the users device just pass in the path and mimetype to a media scanner connection.
conn.scanFile(fos..getAbsolutePath(),"image/*");
**End edit *
fis.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
*Edit setup the mediascanner connection *
private static MediaScannerConnection conn;
somewhere in onCreate()
conn = new MediaScannerConnection(this, this);
conn.connect();
#Override
public void onScanCompleted(String path, Uri uri) {
// now is good time to save stuff in the database because
// the last segment of the uri is the imageId in the mediaStore.
// you can easily pull a thumbnail from the mediaStore with the imageId.
// example of getting thumbnail
//final BitmapFactory.Options bmOptions = new BitmapFactory.Options();
// bmOptions.inSampleSize = 1;
//Bitmap bm = MediaStore.Images.Thumbnails.getThumbnail(
// context.getContentResolver(), newImageId,
// MediaStore.Images.Thumbnails.MINI_KIND,
// bmOptions);
}
#Override
public void onMediaScannerConnected() {
//toast ready
// enable your camera button
}

Intent imageIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
File imagesFolder = new File(Environment.getExternalStorageDirectory(), "MyProjectName");
if (!imagesFolder.exists()) {
imagesFolder.mkdirs();// <----Do Not Forget this
}
SimpleDateFormat sdf = new SimpleDateFormat("ddMMyyyy_HHmmss_Z");
String currentDateandTime = sdf.format(new Date());
String fileName = "image_" + String.valueOf(currentDateandTime) + ".jpg";
File output = new File(imagesFolder, fileName);
Uri uriSavedImage = Uri.fromFile(image);
imageIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
OutputStream imageFileOS;
try {
imageFileOS = getContentResolver().openOutputStream(uriSavedImage);
imageFileOS.write(arg0);
imageFileOS.flush();
imageFileOS.close();
Toast.makeText(AndroidCamera.this,
"Image saved: ",
Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);

Related

Need to select a file and Save it in given folder in android

According to my code that I can select a file after that how can I save that selected file in given directory?
Here I captured Uri but I could not save that audio file in Specific folder.
Where can be the issue?Any mistake which I have done while writing outputStream?
public class Upload extends AppCompatActivity {
File folder;
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.splashscreen);
/* New Handler to start the Menu-Activity
* and close this Splash-Screen after some seconds.*/
folder = new File(Environment.getExternalStorageDirectory() + "/Audios");
File folder1 = new File(Environment.getExternalStorageDirectory() + "/");
if (!folder.exists()) {
folder.mkdir();
}
for (File f : folder.listFiles()) {
if (f.isFile()) {
String name = f.getName();
// System.out.print(name);
Toast.makeText(getApplicationContext(), name, Toast.LENGTH_SHORT).show();
}
// Do your stuff
}
Intent intent_upload = new Intent();
intent_upload.setType("audio/*");
intent_upload.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent_upload, 1);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if (resultCode == RESULT_OK) {
FileInputStream fileInputStream = null;
//the selected audio.
Uri uri = data.getData();
Toast.makeText(getApplicationContext(), uri.getPath(), Toast.LENGTH_SHORT).show();
File test = new File(uri.getPath());
try {
fileInputStream = new FileInputStream(test);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
FileOutputStream outputStream = new FileOutputStream(folder, true);
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int len = 0;
while ((len = fileInputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, len);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
super.onActivityResult(requestCode, resultCode, data);
}
}
This does not "select a file". It allows the user to choose a piece of content.
In onActivityResult(), if the result code is RESULT_OK, the Intent will have a Uri pointing to the selected piece of content. Use ContentResolver and openInputStream() to get an InputStream on that content. From there, do what you need to do, such as open a FileOutputStream to some file and then copy the bytes from the InputStream to the OutputStream.
BTW, ACTION_GET_CONTENT does not take a Uri as input. Replace setDataAndType() with setType().

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.

Android - How to store and retrieve the image from internal storage

I want to take image from camera and store it and view it from internal storage.
I use this code to take image from camera.
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, TAKE_PIC);
I tried the following to save the bitmap in internal storage.
public String saveToInternalSorage(Bitmap bitmapImage, String fileName){
File file = new File(createBasePath(), fileName + ".png");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
return file.getName();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == TAKE_PIC && resultCode == RESULT_OK) {
Intent i=new Intent(Intent.ACTION_VIEW);
i.setDataAndType(Uri.fromFile(output), "image/png");
startActivity(i);
}
}
My path is /data/user/0/com.dev/app/1454351400000/33352/capture_Image1.png
But here I am facing one issue. The bit map size is very small. I want exact image what I taken from camera.
Then I found one solution. Set the path before intent. So I tried like this.
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
output = new File(createBasePath(), "capture_Image1" + ".png");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(output));
startActivityForResult(intent, TAKE_PIC);
When I use this code the image is not showing. on onActivityResult the resultCode showing -1.
If I use the following code
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File dir= Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
output=new File(dir, "CameraContentDemo.png");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(output));
startActivityForResult(intent, TAKE_PIC);
This code is working fine. After taking the image it showing image.
So please let me know store and retrieve the image from internal db with original quality.
Below is code to save the image to internal directory.
private String saveToInternalStorage(Bitmap bitmapImage){
ContextWrapper cw = new ContextWrapper(getApplicationContext());
// path to imageDir
File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
// Now Create imageDir
File mypath=new File(directory,"abc.jpg");
FileOutputStream foss = null;
try {
foss = new FileOutputStream(mypath);
// Using compress method on the BitMap object to write image to the OutputStream
bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, foss);
} catch (Exception e) {
e.printStackTrace();
} finally {
foss.close();
}
return directory.getAbsolutePath();
}
Use below code for Reading a file from internal storage
private void loadImageFromStorage(String path)
{
try {
File f=new File(path, "abc.jpg");
Bitmap b = BitmapFactory.decodeStream(new FileInputStream(f));
ImageView img=(ImageView)findViewById(R.id.imgPicker);
img.setImageBitmap(b);
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
void openMultiSelectGallery() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri =getOutputMediaFile();
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
/* start activity for result pass intent as argument and request code */
startActivityForResult(intent, CAMERA_REQUEEST_CODE);
}
/**
* This method set the path for the captured image from camera for updating
* the profile pic
*/
private Uri getOutputMediaFile() {
File mediaStorageDir = new File(
Environment.getExternalStorageDirectory(), "."
+ Constants.CONTAINER);
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
mediaStorageDir.mkdirs();
}
File mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "IMG_" + System.currentTimeMillis() + ".png");
Uri uri = null;
if (mediaFile != null) {
uri = Uri.fromFile(mediaFile);
}
return uri;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK
&& requestCode == CAMERA_REQUEEST_CODE) {
String path =fileUri.getPath();
//decode the path to bitmap here
}
}

save camera image into directory

I am working on a application in which I have to click the image from the camera and save it into directory.I am able to create directory named MyPersonalFolder and also images are going into it but when I am trying to open that image to see, it doesn't open and shows the message that that image cannot be opened. here is my code. Can anyone please tell me what mistake I am doing here.
I have also mentioned permissions in manifest .
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
public class Camera extends Activity{
private static final String TAG = "Camera";
private static final int CAMERA_PIC_REQUEST = 1111;
Button click , share;
ImageView image;
String to_send;
String filename;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.camera);
image = (ImageView)findViewById(R.id.image);
share = (Button)findViewById(R.id.share);
click = (Button)findViewById(R.id.click);
click.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAMERA_PIC_REQUEST);
}
});
share.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
BitmapDrawable bitmapDrawable = (BitmapDrawable)image.getDrawable();
Bitmap bitmap = bitmapDrawable.getBitmap();
// Save this bitmap to a file.
File cache = getApplicationContext().getExternalCacheDir();
File sharefile = new File(cache, "toshare.png");
try {
FileOutputStream out = new FileOutputStream(sharefile);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
out.close();
} catch (IOException e) {
}
// Now send it out to share
Intent share = new Intent(android.content.Intent.ACTION_SEND);
share.setType("image/*");
share.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + sharefile.getAbsolutePath()));
try {
startActivity(Intent.createChooser(share, "Share photo"));
} catch (Exception e) {
}
/*Intent share = new Intent(Intent.ACTION_SEND);
share.setType("text/plain");
//String to_send = null;
share.putExtra(Intent.EXTRA_TEXT, to_send);
startActivity(Intent.createChooser(share, "Share using..."));*/
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
FileOutputStream outStream = null;
if (requestCode == CAMERA_PIC_REQUEST) {
//2
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
image.setImageBitmap(thumbnail);
//3
share.setVisibility(0);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
//4
try {
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File (sdCard.getAbsolutePath() + "/MyPersonalFolder");
dir.mkdirs();
String fileName = String.format("%d.jpg", System.currentTimeMillis());
File outFile = new File(dir, fileName);
outStream = new FileOutputStream(outFile);
//outStream.write(data[0]);
outStream.flush();
outStream.close();
//Log.d(TAG, "onPictureTaken - wrote bytes: " + data.length + " to " + outFile.getAbsolutePath());
refreshGallery(outFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
/*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();*/
}
}
}
private void refreshGallery(File file) {
Intent mediaScanIntent = new Intent( Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
mediaScanIntent.setData(Uri.fromFile(file));
sendBroadcast(mediaScanIntent);
}
}
You will need to use MediaScanner to notify the system of the new file/directory. You can try something like this after creating and saving the new file:
/**
* Adds the new photo/video to the device gallery, else it will remain only visible via sd card
*
* #param path
*/
public static void addToGallery(Context context, String path) {
MediaScanner scanner = new MediaScanner(path, null);
MediaScannerConnection connection = new MediaScannerConnection(context, scanner);
scanner.connection = connection;
connection.connect();
}
/**
* Scans the sd card for new videos/images and adds them to the gallery
*/
private static final class MediaScanner implements MediaScannerConnection.MediaScannerConnectionClient {
private final String path;
private final String mimeType;
MediaScannerConnection connection;
public MediaScanner(String path, String mimeType) {
this.path = path;
this.mimeType = mimeType;
}
#Override
public void onMediaScannerConnected() {
connection.scanFile(path, mimeType);
}
#Override
public void onScanCompleted(String path, Uri uri) {
connection.disconnect();
}
}
EDIT:
You are also forgetting to write the byte array to the file specified in the output stream, like in the code that you have commented out. Try this at the end just before you refresh the gallery:
outStream = new FileOutputStream(outFile);
outStream.write(bytes.toByteArray()); //this is the line you had missing
outStream.flush();
outStream.close();
Also take note that using Intent.ACTION_MEDIA_SCANNER_SCAN_FILE to refresh the gallery can also present you with some security issues on kitkat (cant remember exactly what the issues were). So just make sure you test it on kitkat device to confirm that it works correctly

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