'Convert MAUI ImageSource to png

I'm rendering a signature on the native canvas for Android, iOS, and windows separately. Now, I need to save this locally, so I have converted the view to stream image source format. But I'm not sure how to convert to PNG and save it locally?.



Solution 1:[1]

You can use Dependency Injection to deal with it, implement the interface on the platform you want.

For example, I did a test on android:

The interface:

      public interface MyService
        {
            public  void Convert( string filename, ImageSource img);
        }
    }

The implemention:

 public class AndroidService : MyService
    {
        public async void Convert(string filename, ImageSource img)
        {
            System.IO.Stream outputStream = null;

            var handler = new FileImageSourceHandler(); 
            Bitmap pic = await handler.LoadImageAsync(img, Android.App.Application.Context);
          
          
            var savedImageFilename = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), filename);
            bool success = false;
            using (outputStream = new System.IO.FileStream(savedImageFilename, System.IO.FileMode.Create))
            {
                if (System.IO.Path.GetExtension(filename).ToLower() == ".png")
                {
                    success = await pic.CompressAsync(Bitmap.CompressFormat.Png, 100, outputStream);
                }
                else
                    success = await pic.CompressAsync(Bitmap.CompressFormat.Jpeg, 100, outputStream);
            }
        }
    }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Adrain Zhu -MSFT