DespeiL
DespeiL

Reputation: 1033

Xamarin.Android Save Image to Gallery Photo Album

I need to save a bitmap to the Gallery using my application name as the album. The path should be:

Gallery->MyAppName->test.png

but the best result that I get looks like:

Gallery->Others->MyAppName->test.png

Here is my code:

using Android.Graphics;
using Android.Media;
using System;
using System.IO;
..
.
.

        public   static  void ExportBitmapAsPNG(Bitmap bitmap)
        {
            var sdCardPath = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath+"/MyAppName";
            if (!Directory.Exists(sdCardPath))
                Directory.CreateDirectory(sdCardPath);

            var filePath = System.IO.Path.Combine(sdCardPath, "test.png");
            var stream = new FileStream(filePath, FileMode.Create);
            bitmap.Compress(Bitmap.CompressFormat.Png, 100, stream);
            stream.Close();
            MediaScannerConnection.ScanFile(Android.App.Application.Context, new string[] { filePath }, null, null);

        }

I hope someone could tell me what I'm missing?

P.S. I tried to use MediaStore, but it's always save in Picture folder and has no overloads to change this.

Android.Provider.MediaStore.Images.Media.InsertImage(ContentResolver, bitmap2, "test", "");

Upvotes: 1

Views: 2979

Answers (1)

Robert Bruce
Robert Bruce

Reputation: 1088

I've rewritten your function to provide that capability. The key difference is how the folder is created. Additionally, I use an Intent for the media scanner. Anyway, I think this should get you where you want to be. Hope this helps!

public void ExportBitmapAsPNG(Bitmap bitmap) {

    // Get/Create Album Folder To Save To
    var jFolder = new Java.IO.File(Environment.GetExternalStoragePublicDirectory(Environment.DirectoryPictures), "MyAppNamePhotoAlbum");
    if (!jFolder.Exists())
        jFolder.Mkdirs();

    var jFile = new Java.IO.File(jFolder, "MyPhoto.jpg");

    // Save File
    using (var fs = new FileStream(jFile.AbsolutePath, FileMode.CreateNew)) {
        bitmap.Compress(Bitmap.CompressFormat.Png, 100, fs);
    }

    // Save Picture To Gallery
    var intent = new Intent(MediaStore.ActionImageCapture);
    intent.PutExtra(MediaStore.ExtraOutput, Android.Net.Uri.FromFile(jFile));
    StartActivityForResult(intent, 0);

    // Request the media scanner to scan a file and add it to the media database
    var f = new Java.IO.File(jFile.AbsolutePath);
    intent = new Intent(Intent.ActionMediaScannerScanFile);
    intent.SetData(Android.Net.Uri.FromFile(f));
    Application.Context.SendBroadcast(intent);

}

Hope this helps!

Upvotes: 1

Related Questions