Wednesday, June 5, 2019

ImageSharp: convert Image to System.Drawing.Bitmap and back

See also on GitHub Gist

namespace Vurdalakov
{
    using System;
    using System.IO;

    using SixLabors.ImageSharp;
    using SixLabors.ImageSharp.Advanced;
    using SixLabors.ImageSharp.Formats.Png;
    using SixLabors.ImageSharp.PixelFormats;

    public static class ImageSharpExtensions
    {
        public static System.Drawing.Bitmap ToBitmap<TPixel>(this Image<TPixel> image) where TPixel : unmanaged, IPixel<TPixel>
        {
            using (var memoryStream = new MemoryStream())
            {
                var imageEncoder = image.GetConfiguration().ImageFormatsManager.FindEncoder(PngFormat.Instance);
                image.Save(memoryStream, imageEncoder);

                memoryStream.Seek(0, SeekOrigin.Begin);

                return new System.Drawing.Bitmap(memoryStream);
            }
        }

        public static Image<TPixel> ToImageSharpImage<TPixel>(this System.Drawing.Bitmap bitmap) where TPixel : unmanaged, IPixel<TPixel>
        {
            using (var memoryStream = new MemoryStream())
            {
                bitmap.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Png);

                memoryStream.Seek(0, SeekOrigin.Begin);

                return Image.Load<TPixel>(memoryStream);
            }
        }
    }
}

2 comments:

  1. Hi Vurdalakov, thanks for posting this utility.
    However, I can't get it working, it complains with Error CS8377 The type 'TPixel' must be a non-nullable value type, along with all fields at any level of nesting, in order to use it as parameter 'TSelf' in the generic type or method 'IPixel'
    I don't fully understand this message. May you give me a clue to progress?

    ReplyDelete
    Replies
    1. Hi Matias, thank you for pointing this up.

      I fixed the example so that it is compatible with the new version of SixLabors.ImageSharp library, namely:
      "where TPixel : struct, IPixel"
      is changed to
      "where TPixel : unmanaged, IPixel"

      Delete