How to save image in android gallery
Asked Answered
S

8

25

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();
        }
Sigismondo answered 31/12, 2013 at 15:35 Comment(2)
Does the folder have a file called ".nomedia"? Check with ES File Explorer, you may need to check hidden files, enable that from the ES File Explorer slide menu.Terrarium
No man no have .nomediaSigismondo
N
79

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);
}
Np answered 31/12, 2013 at 15:49 Comment(9)
I newbie on android how implements your code in my code :/ I need that save image in the file /WhatSappIMG/ :/Sigismondo
add this method to your code, and add this line after the "output.close();": addImageToGallery(file.getAbsolutePath(), YourActivity.this);Np
the code you provided implemented inside Activity class? if so then YourActivity is the Name of your activityNp
if you asked that - then you probably newbie not only on android, but also in javaNp
I can chat with you on skype o another chat ? xDSigismondo
hmm... yes! but in 10 minutes from now. I'm going for 10 minutes now. my skype id is "talkanel"Np
This is the correct answer; trying to use the other answers here results in headache if you're trying to add a PNG file.Cho
FYI - I thought I'd be creative and try sending the byte[] of the image to MediaStore.MediaColumns.DATA instead of the path. DO NOT do this. It corrupted my gallery app and I had to reset the phone.Tatia
How do I save it using custom filename?Peterpeterborough
B
12

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

Bacteroid answered 28/1, 2015 at 5:31 Comment(2)
Can I determine the album's name?Jiffy
@DanielReyhanian Path is: sdcard=>PicturesGmt
D
7

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 "".

Derrick answered 31/12, 2013 at 15:49 Comment(1)
This work but save the image in when imagen of camera i need that save imagen in my directory :/Sigismondo
G
2

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.

Grater answered 26/7, 2018 at 14:14 Comment(1)
I feel like your answer doesn't get enough appreciation. Thanks a lot, you just saved for me tons of hours and my code works perfectly. Also, it's nice to see that people also do care about the ones who use Xamarin.Jiffy
F
2

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()
            }
        }

}
Fortunato answered 9/9, 2020 at 13:0 Comment(0)
C
1

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();
    }
Chassis answered 31/12, 2013 at 15:53 Comment(1)
This compresses the image and the size of the image is changed then.Amphistylar
S
1

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;
}
Spinneret answered 4/6, 2021 at 21:55 Comment(0)
U
0

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();
        }
    }
Unspeakable answered 23/9, 2022 at 4:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.