Xamarin.Forms Android save image to gallery

旧时模样 提交于 2019-12-18 09:45:28

问题


I have a stream which is the result of taking a photo. I want to save that photo to the users Gallery.

I have tried all manner of things but nothing takes... The class I am saving is a plain C# class - it does not inherit form any android types but that could be done if necessary (to fire an intent perhaps - though I tried this and it ended up another rabbit hole)

I have tried this:

try{
    using (FileStream fs = new FileStream(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + _name, FileMode.OpenOrCreate))
    {
        fs.Write(bytes, 0, bytes.Length);
    }
} catch (Exception ex) {
    Console.WriteLine (ex.Message);
}

and also:

        if (_filename.ToLower ().Contains (".jpg") || _filename.ToLower ().Contains (".png")) {
            stream.Position = 0;
            var bitmap = BitmapFactory.DecodeStream (stream);

            var finalStream = new MemoryStream ();

            bitmap.Compress (Bitmap.CompressFormat.Jpeg, 25, finalStream);
            bitmap = null;

            finalStream.Position = 0;

            var path2 = Environment.GetFolderPath (Environment.SpecialFolder.MyPictures);
            var filename2 = System.IO.Path.Combine (path2, _filename);

            using (var fileStream = File.Create (filename2)) {
                finalStream.Seek (0, SeekOrigin.Begin);
                finalStream.CopyTo (fileStream);
                fileStream.Close ();

                finalStream.Dispose ();
                stream.Dispose ();
                fileStream.Dispose ();
                GC.Collect ();
            }
            return;
        }

I thought this would be an easy task! meh...

Any help?


回答1:


Use the MediaStore ContentProvider. MediaStore.Images.Media has several Insert methods you can use to add content to the gallery.



来源:https://stackoverflow.com/questions/31296280/xamarin-forms-android-save-image-to-gallery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!