Search code examples
c#avaloniauiimagesharp

Display ImageSharp Image in Avalonia UI


As the title says. It seems that Avalonia Bitmap requires file path, so the only solution that comes to my mind is saving image, and then displaying it. But it's not exactly what I want to do, I would want to directly display the image from memory.

public void ReadAndDisplayImage()
        {
            ReadWrite rw = new ReadWrite();
            var image = rw.ReadImage(ImagePath); //ImageSharp Image
            SelectedImage = new Avalonia.Media.Imaging.Bitmap(ImagePath); //constructor accepts only string, unable to display ImageSharp Image directly
        }

In this case here displaying from path is fully acceptable, but later I will need to display it without saving.


Solution

  • You can save the Image's data into a memory stream and pass it in to Avalonia's Bitmap.

    public void ReadAndDisplayImage()
    {
        ReadWrite rw = new ReadWrite();
        var image = rw.ReadImage(ImagePath);
        using (MemoryStream ms = new MemoryStream())
        {
            image.Save(ms,PngFormat.Instance);
            SelectedImage = new Avalonia.Media.Imaging.Bitmap(ms);
        }
    }