How to save image in android gallery - android

I try to save the image into WathsappIMG but when I go to image gallery android I don't see the image and the image there into the directory can be seen from ES File Explorer
OutputStream output;
// Find the SD Card path
File filepath = Environment.getExternalStorageDirectory();
// Create a new folder in SD Card
File dir = new File(filepath.getAbsolutePath()
+ "/WhatSappIMG/");
dir.mkdirs();
// Retrieve the image from the res folder
BitmapDrawable drawable = (BitmapDrawable) principal.getDrawable();
Bitmap bitmap1 = drawable.getBitmap();
// Create a name for the saved image
File file = new File(dir, "Wallpaper.jpg" );
try {
output = new FileOutputStream(file);
// Compress into png format image from 0% - 100%
bitmap1.compress(Bitmap.CompressFormat.JPEG, 100, output);
output.flush();
output.close();
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

the gallery don't displaying (necessarily) files from external storage.
this is a common mistake.
the gallery displays images stored on the media store provider
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);
}

here is what you should enter, when you're about to save the picture in the Gallery
MediaStore.Images.Media.insertImage(getContentResolver(), yourBitmap, yourTitle , yourDescription);
That code will add the image at the end of the Gallery. so please, check your Gallery picture, to be sure

Try adding this:
MediaStore.Images.Media.insertImage(getContentResolver(), yourBitmap, yourTitle , yourDescription);
Fill in your details for yourBitmap, yourTitle, and yourDescription, or just leave it as "".

You need to add a MediaScannerConnection class to your function of saving the image to the gallery. This class scans for new files and folders in gallery connected with your app. Add the following class to scan the newly saved image files or new added image directory to the gallery or download Source Code
MediaScannerConnection.scanFile(this, new String[]{file.toString()}, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.i("ExternalStorage", "Scanned " + path + ":");
Log.i("ExternalStorage", "-> uri=" + uri);
}
});
Read more

For Xamarin fellows:
public static void SaveToTheGalley(this string filePath, Context context)
{
var values = new ContentValues();
values.Put(MediaStore.Images.Media.InterfaceConsts.DateTaken, Java.Lang.JavaSystem.CurrentTimeMillis());
values.Put(MediaStore.Images.Media.InterfaceConsts.MimeType, "image/jpeg");
values.Put(MediaStore.MediaColumns.Data, filePath);
context.ContentResolver.Insert(MediaStore.Images.Media.ExternalContentUri, values);
}
And don't forget about android.permission.WRITE_EXTERNAL_STORAGE permission.

As
MediaStore.MediaColumns.Data
and
MediaStore.Images.Media.insertImage
is deprecated now,
here is how I did it using bitmap
fun addImageToGallery(
fileName: String,
context: Context,
bitmap: Bitmap
) {
val values = ContentValues()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
values.put(MediaStore.Images.Media.DATE_TAKEN, System.currentTimeMillis())
}
values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg")
values.put(MediaStore.Images.ImageColumns.DISPLAY_NAME, fileName)
values.put(MediaStore.Images.ImageColumns.TITLE, fileName)
val uri: Uri? = context.contentResolver.insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
values
)
uri?.let {
context.contentResolver.openOutputStream(uri)?.let { stream ->
val oStream =
BufferedOutputStream(stream)
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, oStream)
oStream.close()
}
}
}

You should change this piece of code-
try {
output = new FileOutputStream(file);
// Compress into png format image from 0% - 100%
bitmap1.compress(Bitmap.CompressFormat.JPEG, 100, output);
output.flush();
output.close();
String url = Images.Media.insertImage(getContentResolver(), bitmap1,
"Wallpaper.jpg", null);
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Kindly refer this code worked for me:
public static boolean saveImageToGallery(Context context, Bitmap bmp) {
// First save the picture
String storePath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "dearxy";
File appDir = new File(storePath);
if (!appDir.exists()) {
appDir.mkdir();
}
String fileName = System.currentTimeMillis() + ".jpg";
File file = new File(appDir, fileName);
try {
FileOutputStream fos = new FileOutputStream(file);
//Compress and save pictures by io stream
boolean isSuccess = bmp.compress(Bitmap.CompressFormat.JPEG, 60, fos);
fos.flush();
fos.close();
//Insert files into the system Gallery
//MediaStore.Images.Media.insertImage(context.getContentResolver(), file.getAbsolutePath(), fileName, null);
//Update the database by sending broadcast notifications after saving pictures
Uri uri = Uri.fromFile(file);
context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
if (isSuccess) {
return true;
} else {
return false;
}
} catch (IOException e) {
e.printStackTrace();
}
return false;
}

Use the following code to make your image visible in the gallery.
public void saveImageToGallery(Context context, Uri path) {
// Create image from the Uri for storing it in the preferred location
Bitmap bmp = null;
ContentResolver contentResolver = getContentResolver();
try {
if(Build.VERSION.SDK_INT < 28) {
bmp = MediaStore.Images.Media.getBitmap(contentResolver, path);
} else {
ImageDecoder.Source source = ImageDecoder.createSource(contentResolver, path);
bmp = ImageDecoder.decodeBitmap(source);
}
} catch (Exception e) {
e.printStackTrace();
}
// Store image to internal storage/ImagePicker directory
String storePath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "ImagePicker";
File appDir = new File(storePath);
if (!appDir.exists()) {
appDir.mkdir();
}
String fileName = System.currentTimeMillis() + ".jpg";
File file = new File(appDir, fileName);
try {
FileOutputStream fos = new FileOutputStream(file);
boolean isSuccess = bmp.compress(Bitmap.CompressFormat.JPEG, 60, fos);
fos.flush();
fos.close();
// Broadcast the image & make it visible in the gallery
Uri uri = Uri.fromFile(file);
context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
if (isSuccess) {
Toast.makeText(context, "File saved to gallery", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "Failed to save", Toast.LENGTH_SHORT).show();
}
} catch (IOException e) {
e.printStackTrace();
}
}

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;
}

Save image from camera without being resized

I use the following code to create image file and save them in to sd card
private File createImageFile(Bitmap bitmap) throws IOException {
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
PICNAME,
".png",
storageDir);
FileOutputStream out = null;
try {
out = new FileOutputStream(image);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
} catch (IOException e) {
e.printStackTrace();
}
return image;
}
The issue is that, though I take picture in full screen mode but the above code always saves the image in very less amount of dimension which is 320x240. why so.. is there by any means that I can save the image without resizing?
you can do it like this :
public static Uri takePhotoByCamera(Activity activity) {
File publicDirectory = Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES + "/myFolder");
double d = new Random().nextDouble();
File file = new File(publicDirectory, d + ".jpg");
String path = file.getAbsolutePath();
ContentValues values = new ContentValues();
values.put(MediaStore.MediaColumns.DATA, path);
values.put(MediaStore.MediaColumns.TITLE, "New Picture");
values.put(MediaStore.Images.ImageColumns.DESCRIPTION, "From your Camera");
activity.getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Uri photoUri = Uri.parse("file://" + path);
if (!publicDirectory.exists())
publicDirectory.mkdirs();
else if (!publicDirectory.isDirectory() && publicDirectory.canWrite()) {
publicDirectory.delete();
publicDirectory.mkdirs();
} else {
Log.d("tag550", "can't access");
}
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
activity.startActivityForResult(intent, requestCamera);
return photoUri;
}

save image in gallery android

I am using this code to save the image:
URL url = null;
try {
url = new URL("image");
} catch (MalformedURLException e1) {
e1.printStackTrace();
}
Bitmap bmp = null;
try {
bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
} catch (IOException e1) {
e1.printStackTrace();
}
OutputStream output;
File filepath = Environment.getExternalStorageDirectory();
File dir = new File(filepath.getAbsolutePath() + "/folder name/");
dir.mkdirs();
File file = new File(dir, image + ".png");
Toast.makeText(HomeActivity.this, "Image Saved to SD Card", Toast.LENGTH_SHORT).show();
try {
output = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.PNG, 100, output);
output.flush();
output.close();
}
catch (Exception e) {
e.printStackTrace();
}
The issue is when this code runs on lollipop devices, Images are not showing in gallery. I have to install File Manager to check these images.
With this code:
MediaStore.Images.Media.insertImage(getContentResolver(), bmp, "image";
Images are saved in camera folder.
I want to show images in gallery with a specific folder name in all android devices.
Please help.
public void saveImageToExternal(String imgName, Bitmap bm) throws IOException {
//Create Path to save Image
File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES+appFolder); //Creates app specific folder
path.mkdirs();
File imageFile = new File(path, imgName+".png"); // Imagename.png
FileOutputStream out = new FileOutputStream(imageFile);
try{
bm.compress(Bitmap.CompressFormat.PNG, 100, out); // Compress Image
out.flush();
out.close();
// Tell the media scanner about the new file so that it is
// immediately available to the user.
MediaScannerConnection.scanFile(context,new String[] { imageFile.getAbsolutePath() }, null,new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.i("ExternalStorage", "Scanned " + path + ":");
Log.i("ExternalStorage", "-> uri=" + uri);
}
});
} catch(Exception e) {
throw new IOException();
}
}
Worked for me.
Thanks for your time
Just you are code is missing the MediaScannerConnection class. This class scans for new files and directories in gallery that are created from your app. See a full demo example demonstrating this. http://whats-online.info/science-and-tutorials/135/how-to-save-an-image-to-gallery-in-android-programmatically/
This Worked for me.
Add MediaScannerConnection to scan the file. Specify the file url and mimeType
MediaScannerConnection.scanFile(context,new String[] { image.getAbsolutePath() },
new String[] {"images/*"}, new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.i("ScanCompleted", "Scanned " + path + ":");
}
});
Just change these lines, it will work -
File filepath = Environment.getExternalStorageDirectory().toString();
File dir = new File(filepath + "/folder name/");
dir.mkdirs();
File file = new File(dir, image + ".png");
If you want to save an Image inside a directory then this Code worked for me!
saveImage(data);
private void saveImage(Bitmap data) {
File createFolder = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),"test");
if(!createFolder.exists())
createFolder.mkdir();
File saveImage = new File(createFolder,"downloadimage.jpg");
try {
OutputStream outputStream = new FileOutputStream(saveImage);
data.compress(Bitmap.CompressFormat.JPEG,100,outputStream);
outputStream.flush();
outputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

Android save images not update to gallery

I'm trying to save my images from ImageView to sd card and they are saving to sd card but they are not updating to gallery. Here is my code.
public void save(View v) {
bitmap = BitmapFactory.decodeResource(getResources(), backgrounds.get(currentPosition)) ;
File filepath = Environment.getExternalStorageDirectory();
File dir = new File(filepath.getAbsolutePath()
+ "/Folder/");
dir.mkdirs();
String Image = System.currentTimeMillis()+".Png";
File file = new File(dir, Image);
Toast.makeText(MainActivity.this, "Image Saved to SD Card",
Toast.LENGTH_SHORT).show();
try {
output = new FileOutputStream(file);
// Compress into png format image from 0% - 100%
bitmap.compress(Bitmap.CompressFormat.PNG, 100, output);
output.flush();
output.close();
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
You have to first add mime type to the image
it will work.
MediaScannerConnection.scanFile(
context,
new String[]{ pathToFile1, pathToFile2 },
new String[]{ "audio/mp3", "*/*" },
new MediaScannerConnectionClient()
{
public void onMediaScannerConnected()
{
}
public void onScanCompleted(String path, Uri uri)
{
}
});
Once you saved bitmap as PNG file in sdCard.
Make sure that Gallery knows that PNG file has been created.
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
Uri contentUri = Uri.fromFile(file);
mediaScanIntent.setData(contentUri);
context.sendBroadcast(mediaScanIntent);

Android, How to retrieve the image previously save and display when required

I used this code below to save an image taken from the camera intent, to a folder in the gallery, which worked great. I'd like to retrieve the image to display on an ImageView within an activity when asked, though after trying various methods/code, nothing so far has worked. Given the path/code used to save the image, could someone point me in the right direction of how to get it back. Thanks in advance - Jim.
public void SaveImage(Context context,Bitmap ImageToSave, String fileName){
TheThis = context;
String file_path = Environment.getExternalStorageDirectory()+ NameOfFolder;
// String CurrentDateAndTime= getCurrentDateAndTime();
File dir = new File(file_path);
if(!dir.exists()){
dir.mkdirs();
}
File file = new File(dir, fileName + ".jpg");
try {
FileOutputStream fOut = new FileOutputStream(file);
ImageToSave.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
fOut.flush();
fOut.close();
MakeSureFileWasCreatedThenMakeAvabile(file);
AbleToSave();
}
catch (FileNotFoundException e) {UnableToSave();}
catch (IOException e){UnableToSave();}
}
private void MakeSureFileWasCreatedThenMakeAvabile(File file) {
MediaScannerConnection.scanFile(TheThis,
new String[] { file.toString() }, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.e("ExternalStorage", "Scanned " + path + ":");
Log.e("ExternalStorage", "-> uri=" + uri);
}
});
}
If you have a proper path and permissions, here is the code working perfectly for me
File rootsd = Environment.getExternalStorageDirectory();
String rootPath = rootsd.getAbsolutePath();
String pathName = rootPath + "your path here" + "image name here";
try {
Drawable d = Drawable.createFromPath(pathName);
layout.setBackgroundDrawable(d);
} catch (Exception e) {
e.printStackTrace();
}
Hope this helps and enjoy your work.

Categories

Resources