I have followed and literally picked up code from other answers but its still not working.
When a picture is clicked, it's saved by default in DCIM/camera with name such as 20150910_111841.jpg (date_timeInMilliseconds) but I want to save it as "myName_date.jpg".
public void OnClick(){
if (items[item].equals("Take Photo")) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
f = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
mMediaUri=Uri.fromFile(new File(f, "MEDIT"+System.currentTimeMillis()+"jpg"));
intent.putExtra(MediaStore.EXTRA_OUTPUT, mMediaUri);
startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode==RESULT_OK){
switch(requestCode) {
case REQUEST_IMAGE_CAPTURE:
Bitmap bm = BitmapFactory.decodeFile(mMediaUri.getPath());
//imgVIew.setImageBitmap(bm);
Bitmap scaledBitmap=ScaleImage(bm);
final ByteArrayOutputStream bos = new ByteArrayOutputStream();
scaledBitmap.compress(Bitmap.CompressFormat.JPEG,100, bos);
//Bitmap decoded = BitmapFactory.decodeStream(new ByteArrayInputStream(bos.toByteArray()));
imgVIew.setImageBitmap(scaledBitmap);
imageView.setImage(ImageSource.bitmap(scaledBitmap));
imageView1.setImage(ImageSource.bitmap(bm));
break;
case REQUEST_GALLERY:
//Uri selectedImage = imageReturnedIntent.getData();
//imageview.setImageURI(selectedImage);
break;
}//Close switch statement
}else {
Log.d("Error ", "user canceled !");
}
}
I have not yet added code for the gallery part but that shouldn't be a problem. As of now no matter what I do its being saved as default but I realized if people don't have an SD card then it can cause an issue. I'd rather have this picture available, in the default DCIM location but with a custom name. Thanks!
Try the below code to save the image with the name you want:
/** 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");
*/
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DCIM), "the_name_of_directory");
// 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("canberra trailpass", "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 +
"myName"+ timeStamp + ".jpg");
} else {
return null;
}
return mediaFile;
}
To use a custom name, replace this -
mMediaUri=Uri.fromFile(new File(f, "MEDIT"+System.currentTimeMillis()+"jpg"));
With this -
mMediaUri=Uri.fromFile(new File(f, "MEDIT"+"Your Custom Name"+System.currentTimeMillis()+"jpg"));
It will like, this
File fPath = getAlbumStorageDir("myName_date");
File f = new File(fPath, "myName_date" + Calendar.getInstance().getTimeInMillis() + ".jpg");
It's not a device problem,
as example my working code, i have achieve like this,
public static Uri getUri(String filePath) {
File media = new File(filePath);
Uri uri = Uri.fromFile(media);
return uri;
}
public static File getAlbumStorageDir(String albumName) {
File file = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), albumName);
if (file.exists()) {
Log.d(LOGTAG, "storeage file exists");
}
if (!(file.mkdirs() || file.isDirectory())) {
Log.e(LOGTAG, "Directory not created");
}
return file;
}
public static class SaveImageTask extends AsyncTask<Bitmap, Void, String> {
private SaveImageListener listener;
public SaveImageTask(SaveImageListener listener) {
this.listener = listener;
}
#Override
protected String doInBackground(Bitmap... params) {
Bitmap bitmapToSave = params[0];
File fPath = getAlbumStorageDir("AppName");
File f = new File(fPath, "AppName" + Calendar.getInstance().getTimeInMillis() + ".jpg");
String filePath = null;
try {
FileOutputStream strm = new FileOutputStream(f);
bitmapToSave.compress(Bitmap.CompressFormat.JPEG, 100, strm);
strm.close();
filePath = f.getPath();
} catch (IOException e) {
e.printStackTrace();
}
return filePath;
}
#Override
protected void onPostExecute(String filePath) {
super.onPostExecute(filePath);
listener.onImageSaved(filePath);
}
interface SaveImageListener {
void onImageSaved(String filePath);
}
}
Uri mImageCaptureUri;
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
mImageCaptureUri = Uri.fromFile(new File(Environment
.getExternalStorageDirectory(), "example.jpg"));
takePictureIntent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT,
mImageCaptureUri);
startActivityForResult(takePictureIntent, 1);
onActivityResult :
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK) {
switch (requestCode) {
case 1:
if(mImageCaptureUri!=null) {
imageName = "";
Bitmap bitmap = getCameraImage(activity, mImageCaptureUri);
imgView.setImageBitmap(bitmap );
removeFile(mImageCaptureUri.getPath());
break;
}
}
}
get camera image :
public static Bitmap getCameraImage(Activity activity, Uri mImageCaptureUri){
if(mImageCaptureUri==null) {
return null;
} else {
activity.getContentResolver().notifyChange(mImageCaptureUri, null);
ContentResolver cr = activity.getContentResolver();
Bitmap bitmap = null;
try {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 6;
AssetFileDescriptor fileDescriptor =null;
fileDescriptor =
cr.openAssetFileDescriptor( mImageCaptureUri, "r");
bitmap
= BitmapFactory.decodeFileDescriptor(
fileDescriptor.getFileDescriptor(), null, options);
//bitmap = android.provider.MediaStore.Images.Media.getBitmap(cr, mImageCaptureUri);
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
}
Related
Hello everyone! I am using a camera which saves photo's in the phones gallery. But I don't want to save the photo in the gallery. I want to save it somewhere else. So all i need is not to save it automatically in the gallery.
This is my code:
public class MainActivity extends AppCompatActivity {
ImageView photo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button click = (Button)findViewById(R.id.btnPhoto);
photo = (ImageView) findViewById(R.id.imgPhoto);
click.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, 0);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Bitmap bitmap = (Bitmap)data.getExtras().get("data");
photo.setImageBitmap(bitmap);
}
}
If my question is not good enough, please ask me! And please help me out.
This method for open camera and path is File declare global.
private void openCamera() {
Logger.i("openCamera");
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(this.getPackageManager()) != null) {
File rootPath = new File(Environment.getExternalStorageDirectory(), "folderName");
if (!rootPath.exists())
rootPath.mkdirs();
DateFormat df = new SimpleDateFormat("yyyy-MM-dd-kk-mm-ss");
String snapshotImage = df.format(new Date()) + ".jpg";
rootPath = new File(rootPath + "/" + snapshotImage);
path = rootPath;
takePictureIntent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, Uri.fromFile(path));
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
get result
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 8;
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
FileOutputStream fos = null;
try {
// Float Latitude=0.0f, Longitude=0.0f;
imageDvr.setImageURI(Uri.parse(path.getAbsolutePath()));
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
}
}
}
}
}
}
and also give per\mission in manifest file
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
You will get the bitmap of image in onActivityResult(), and you will store that Image by bitmap.
Use below function to store image on your self made folder. you need to make that folder and need to use path of that.
like this.
public void SaveImage(Bitmap showedImgae){
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/YourSelfMadeFolder");
myDir.mkdirs();
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "FILENAME-"+ n +".jpg";
File file = new File (myDir, fname);
if (file.exists ()) file.delete ();
try {
FileOutputStream out = new FileOutputStream(file);
showedImgae.compress(Bitmap.CompressFormat.JPEG, 100, out);
Toast.makeText(activityname.this, "Image Saved", Toast.LENGTH_SHORT).show();
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
Uri contentUri = Uri.fromFile(file);
mediaScanIntent.setData(contentUri);
getApplicationContext().sendBroadcast(mediaScanIntent);
}
You can add intent android.provider.MediaStore.EXTRA_OUTPUT with your URI:
private File getOutputMediaFile() {
File mediaStorageDir = null;
String state = Environment.getExternalStorageState();
if (state.contains(Environment.MEDIA_MOUNTED)) {
mediaStorageDir = new File(Environment
.getExternalStorageDirectory().toString() + "/yourFolderName");
} else {
mediaStorageDir = new File(Environment
.getExternalStorageDirectory().toString() + "/yourFolderName");
}
if (!mediaStorageDir.exists()) {
Logger.d("Desc", "File dir " + mediaStorageDir.mkdirs());
}
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"Image_" + timeStamp + ".jpg");
return mediaFile;
}
your button click:
click.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Uri mImageCaptureUri = null;
File mediaFile = getOutputMediaFile();
mImageCaptureUri = Uri.fromFile(mediaFile);
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, mImageCaptureUri);
intent.putExtra("return-data", true);
this.startActivityForResult(intent, REQUEST_CODE_TAKE_PICTURE);
}}0;
on activity result:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.d("FilePath","Path"+mediaFile.getAbsolutePath();)
}
I want to save the image without compressing it and want to save it in it's original form i.e. when image is compressed the image size decreases and image become small. I am using native camera for this purpose. I am working in android studio. I am making an app in which i am using a camera to save image. But the image is compressed and is very small and very lower quality.
Below is my code for saving image
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
final LocationSettingsStates states = LocationSettingsStates.fromIntent(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);
}
}
}else {
switch (requestCode) {
case 1000:
switch (resultCode) {
case Activity.RESULT_OK:
// All required changes were successfully made
getLocation();
break;
case Activity.RESULT_CANCELED:
// The user was asked to change settings, but chose not to
Toast.makeText(this, "Location Service not Enabled", Toast.LENGTH_SHORT).show();
break;
default:
break;
}
break;
}
}
}
private void SaveImage(Bitmap finalBitmap) {
File storageDir = new File (String.valueOf(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)));
String root = storageDir + Environment.getExternalStorageDirectory().getAbsolutePath().toString();
Log.v(LOG_TAG, root);
File myDir = new File(root + "/captured_images");
if (!myDir .exists())
{
myDir .mkdirs();
}
Random generator = new Random();
int n = 1000;
n = generator.nextInt(n);
String fname = "Image-" + n + ".jpg";
File file = new File(myDir,fname);
try {
file.createNewFile();
MediaScannerConnection.scanFile(getApplicationContext(), 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();
}
}
Update 1
For more understanding i am putting my onClick method
btn_camera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Check permission for camera
if(ActivityCompat.checkSelfPermission(MainActivity.this, CAMERA)
!= PackageManager.PERMISSION_GRANTED)
{
// Check Permissions Now
// Callback onRequestPermissionsResult interceptado na Activity MainActivity
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{CAMERA},
MainActivity.REQUEST_CAMERA);
}
else {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE );
}
}
});
I searched the solution and found that i can use AndroidBitmapUtil
class so i copy and pasted this class into my project i.e. i created a new class. But i don't know how to use it. Although it is described that i can save image by doing new AndroidBmpUtil().save(bmImage, file);. But again i can't match with my code :(
Any help would be highly appreciated
new AndroidBmpUtil().save(source, sdcardBmpPath);
USER ABOVE LINE OF CODE AND FOLLOW BELOW LINK
https://github.com/ultrakain/AndroidBitmapUtil
Open Camera and save image into some specific directory.
solution number 1
private String pictureImagePath = "";
private void openBackCamera() {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = timeStamp + ".jpg";
File storageDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
pictureImagePath = storageDir.getAbsolutePath() + "/" + imageFileName;
File file = new File(pictureImagePath);
Uri outputFileUri = Uri.fromFile(file);
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(cameraIntent, 1);}
Handle Image
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
File imgFile = new File(pictureImagePath);
if(imgFile.exists()){
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
ImageView myImage = (ImageView) findViewById(R.id.imageviewTest);
myImage.setImageBitmap(myBitmap);
}
}
solution number 2
I have used the following code and this works perfectly fine for me.
values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, "New Picture");
values.put(MediaStore.Images.Media.DESCRIPTION, "From your Camera");
imageUri = getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intent, PICTURE_RESULT);
and also
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case PICTURE_RESULT:
if (requestCode == PICTURE_RESULT)
if (resultCode == Activity.RESULT_OK) {
try {
thumbnail = MediaStore.Images.Media.getBitmap(
getContentResolver(), imageUri);
imgView.setImageBitmap(thumbnail);
imageurl = getRealPathFromURI(imageUri);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
and
public String getRealPathFromURI(Uri contentUri) {
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(contentUri, proj, null, null, null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
For opening camera use
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(android.os.Environment.getExternalStorageDirectory(), "imagename.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
startActivityForResult(intent, 1);
and in your onActivityresult method use
if (requestCode == 1) {
File f = new File(Environment.getExternalStorageDirectory().toString());
for (File temp : f.listFiles()) {
if (temp.getName().equals("imagename.jpg")) {
f = temp;
break;
}
}
try {
Bitmap bitmap;
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(),bitmapOptions);
yourimageview.setImageBitmap(bitmap);
} catch (Exception e) {
e.printStackTrace();
}
}
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
}
}
I am working on a basic camera app. I can take a photo, and I can see it in my app. But I want to see my photo in gallery asynchronous. When restart the phone, I can see my photo in the gallery.
Sample code.
public class PhotosActivity extends Fragment implements View.OnClickListener {
private final int REQUEST_CODE = 100;
private Button fotobutton;
private ImageView foto_image;
private static final String IMAGE_DIRECTORY_NAME = "OlkunMustafa";
public static final int MEDIA_TYPE_IMAGE = 1;
private Uri fileUri;
// Directory name to store captured images and videos
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.photos_activity,container,false);
fotobutton = (Button) rootView.findViewById(R.id.fotobutton);
foto_image = (ImageView) rootView.findViewById(R.id.foto_image);
fotobutton.setOnClickListener(this);
return rootView;
}
#Override
public void onClick(View v) {
if( v == fotobutton) {
Intent photo_intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFile(MEDIA_TYPE_IMAGE);
photo_intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(photo_intent,100);
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == getActivity().RESULT_OK)
{
BitmapFactory.Options options = new BitmapFactory.Options();
final Bitmap bitmap = BitmapFactory.decodeFile(fileUri.getPath(),
options);
foto_image.setImageBitmap(bitmap);
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
Uri contentUri = getOutputMediaFile(MEDIA_TYPE_IMAGE);
mediaScanIntent.setData(contentUri);
getActivity().sendBroadcast(mediaScanIntent);
}
}
private static Uri getOutputMediaFile(int type) {
// External sdcard location
File mediaStorageDir = new File(
Environment
.getExternalStorageDirectory(),
IMAGE_DIRECTORY_NAME);
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
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 Uri.fromFile(mediaFile);
}
}
How can I do it?
You need to call a broadcast to tell Android OS that you have added an Image
First Method
private void galleryAddPic()
{
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
{
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File("file://"+ Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES));
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
}
else
{
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + Environment.getExternalStorageDirectory())));
}
}
Second Method
Or Call
ctx.sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,Uri.parse("file://" + Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES))));
Also have a look on this answer
you can use this method to store image file on media store provider:
public static void addImageToGallery(final String filePath, final Context context) {
ContentValues values = new ContentValues();
values.put(Images.Media.DATE_TAKEN, System.currentTimeMillis());
values.put(Images.Media.MIME_TYPE, "image/jpeg");
values.put(MediaStore.MediaColumns.DATA, filePath);
context.getContentResolver().insert(Images.Media.EXTERNAL_CONTENT_URI, values);
}
And ScanListener
You can directly save image to Gallery
MediaStore.Images.Media.insertImage(getContentResolver(), yourBitmap, yourTitle , yourDescription);
Try using this logic :
private static int TAKE_PICTURE = 1;
private Uri imageUri;
public void takePhoto(View view) {
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
File photo = new File(Environment.getExternalStorageDirectory(), "Pic.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photo));
imageUri = Uri.fromFile(photo);
startActivityForResult(intent, TAKE_PICTURE);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case TAKE_PICTURE:
if (resultCode == Activity.RESULT_OK) {
Uri selectedImage = imageUri;
getContentResolver().notifyChange(selectedImage, null);
ImageView imageView = (ImageView) findViewById(R.id.ImageView);
ContentResolver cr = getContentResolver();
Bitmap bitmap;
try {
bitmap = android.provider.MediaStore.Images.Media
.getBitmap(cr, selectedImage);
imageView.setImageBitmap(bitmap);
Toast.makeText(this, selectedImage.toString(),
Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(this, "Failed to load", Toast.LENGTH_SHORT)
.show();
Log.e("Camera", e.toString());
}
}
}
}
I have a fragment that takes a canvas drawing and saves it to external memory. I go into the device by connecting the USB and searching the file directory. I find it under Android/data/appname/files/img/nameofimage.png. Now I have a 2nd fragment that is saving pictures when the camera takes them but I can't find them.
Camera
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// Check that request code matches ours:
if (requestCode == CALL_BACK) {
// Check if your application folder exists in the external storage,
// if not create it:
File imageStorageFolder = new File(
Environment.getExternalStorageDirectory() + File.separator
+ "Camera");
if (!imageStorageFolder.exists()) {
imageStorageFolder.mkdirs();
Log.d("FILE",
"Folder created at: " + imageStorageFolder.toString());
}
// Check if data in not null and extract the Bitmap:
if (data != null) {
String filename = "image";
String fileNameExtension = ".jpg";
File sdCard = Environment.getExternalStorageDirectory();
String imageStorageFolderName = File.separator + "Camera"
+ File.separator;
File destinationFile = new File(sdCard, imageStorageFolderName
+ filename + fileNameExtension);
Log.d("FILE", "the destination for image file is: "
+ destinationFile);
if (data.getExtras() != null) {
Bitmap bitmap = (Bitmap) data.getExtras().get("data");
try {
FileOutputStream out = new FileOutputStream(
destinationFile);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
out.close();
} catch (Exception e) {
Log.e("FILE", "ERROR:" + e.toString());
}
}
}
}
}
Canvas
capSig.setView(sign = new Sign(this.getActivity(), null))
.setMessage(R.string.store_question)
.setPositiveButton(R.string.save,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
try {
sign.setDrawingCacheEnabled(true);
sign.getDrawingCache()
.compress(
Bitmap.CompressFormat.PNG,
10,
new FileOutputStream(
new File(
getActivity()
.getExternalFilesDir(
"img"),
"signature.png")));
} catch (Exception e) {
Log.e("Error ", e.toString());
}
onClick
private class ClickListener implements View.OnClickListener {
#Override
public void onClick(View v) {
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
startActivityForResult(intent, CALL_BACK);
}
}
I don't fully understand the code, why is this saving to a different location. Also what would I need to do to get it to save under Android/data/appname/files/Camera/ ?
edit
the logcat tells me its being saved here: 06-08 16:21:49.333: D/FILE(4818): the destination for image file is: /storage/emulated/0/Camera/image.jpg Which I assume is listed as private in the files and that's why I cant find it. This does not tell me why its being saved here though.
2nd Edit
Current Code
private class ClickListener implements View.OnClickListener {
#Override
public void onClick(View v) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File sdCard = Environment.getExternalStorageDirectory();
String path = sdCard.getAbsolutePath() + "/Camera" ;
File dir = new File(path);
if (!dir.exists()) {
if (dir.mkdirs()) {
}
}
String FileName = "image";
File file = new File(path, FileName + ".jpg");
Uri outputFileUri = Uri.fromFile(file);
intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(intent, CALL_BACK);
}
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// Check that request code matches ours:
if (requestCode == CALL_BACK) {
Log.v("RESULT", "Picture Taken");
}
}
Try this code
private void TakePhoto() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File sdCard = Environment.getExternalStorageDirectory();
String path = sdCard.getAbsolutePath() + "/Camera" ;
File dir = new File(path);
if (!dir.exists()) {
if (dir.mkdirs()) {
}
}
String FileName = "image";
File file = new File(path, FileName + ".jpg");
Uri outputFileUri = Uri.fromFile(file);
intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(intent, TAKE_PICTURE);
}
Remember
You need this Permission in your Manifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />