2

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;
}
Opi
  • 183
  • 2
  • 12
  • 2
    try Jpeg or Png, not `Bmp`. And be sure to reset your stream to the beginning after writing to it – Jason May 08 '22 at 11:50
  • Testing on Windows, Android, or iOS? – ToolmakerSteve May 08 '22 at 19:51
  • It seems that this is the problem in `ImageSource.FromStream`, I had test it with `Assembly assembly = GetType().GetTypeInfo().Assembly; Stream stream = assembly.GetManifestResourceStream("MauiApp1.Resources.Images.download.jpg"); image.Source = ImageSource.FromStream(() => stream);` and the Image is blank. But when I use the `image.Source = ImageSource.FromFile("download.jpg");`, the image will show the content. – Liyun Zhang - MSFT May 09 '22 at 08:35
  • 1
    And if the platform is android, you can check this [link](https://github.com/dotnet/maui/issues/6583). – Liyun Zhang - MSFT May 09 '22 at 08:41

1 Answers1

0

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);
dominikz
  • 45
  • 5