Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
SixLabors.ImageSharp extensions: convert Image<TPixel> to byte array and System.Drawing.Bitmap etc.
namespace Vurdalakov
{
using System;
using System.IO;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Advanced;
using SixLabors.ImageSharp.Formats;
using SixLabors.ImageSharp.Formats.Png;
using SixLabors.ImageSharp.PixelFormats;
public static class ImageSharpExtensions
{
public static Byte[] ToArray<TPixel>(this Image<TPixel> image, IImageFormat imageFormat) where TPixel : unmanaged, IPixel<TPixel>
{
using (var memoryStream = new MemoryStream())
{
var imageEncoder = image.GetConfiguration().ImageFormatsManager.FindEncoder(imageFormat);
image.Save(memoryStream, imageEncoder);
return memoryStream.ToArray();
}
}
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);
}
}
}
}
@vurdalakov

This comment has been minimized.

Copy link
Owner Author

@vurdalakov vurdalakov commented May 17, 2020

Fixed 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 'TPixel' in the generic type or method 'Image'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.