How to convert System.Drawing.Image to Microsoft.Maui.Controls.Image?

4.7k Views Asked by At

I'm using a library (spire.pdf) to extract images from a PDF file that I ask from the user. The library returns me an array of System.Drawing.Image and I'm currently trying to figure out how to convert those to Microsoft.Maui.Controls.Image

First, I'm storing the System.Drawing.Image in a MemoryStream, which does work correctly (see screenshot). But my output Maui Image doesn't get any content. (ImageSource.FromStream)

Am I missing something here? I'm adding my Convert method here, Thanks in advance for the help!

enter image description here

private Image Convert(System.Drawing.Image img)
{
    MemoryStream stream = new MemoryStream();
    img.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp);

    Image output = new Image()
    {
        Source = ImageSource.FromStream(() => stream)
    };

    return output;
}
1

There are 1 best solutions below

0
On

I ran into the same problem: ImageSource.FromStream(..) does not work properly for me on Windows 11 and returns empty images.

I created a class for a fake local file so I can call ImageSource.FromFile(..) instead:

Fake Local File:

internal class FakeLocalFile : IDisposable
{
    public string FilePath { get; }

    /// <summary>
    /// Currently ImageSource.FromStream is not working on windows devices.
    /// This class saves the passed stream in a cache directory, returns the local path and deletes it on dispose.
    /// </summary>
    public FakeLocalFile(Stream source)
    {
        FilePath = Path.Combine(FileSystem.Current.CacheDirectory, $"{Guid.NewGuid()}.tmp");
        using var fs = new FileStream(FilePath, FileMode.Create);
        source.CopyTo(fs);
    }

    public void Dispose()
    {
        if (File.Exists(FilePath))
            File.Delete(FilePath);
    }
}

Call:

var fakeFile = new FakeLocalFile(info.Data);
Img.Source = ImageSource.FromFile(fakeFile.Path);