How to save image in android gallery

Viewed 84589

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();
        }
9 Answers

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

}

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