using OpenMacroBoard.SDK.Internals;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.PixelFormats;
using SixLabors.ImageSharp.Processing;
using System;
namespace OpenMacroBoard.SDK {
///
/// A collection of extensions for interop with ImageSharp.
///
public static class ImageSharpExtensions {
///
/// Converts an Bgr24 image to a byte array containing raw pixel data.
///
public static byte[] ToBgr24PixelArray(this Image image) {
using var ctx = image.WithBgr24();
var data = new byte[image.Width * image.Height * 3];
ctx.Item.CopyPixelDataTo(data);
return data;
}
///
/// Copies an as Bgr24 into a given span.
///
public static void ToBgr24PixelArray(this Image image, Span targetPixelData) {
using var ctx = image.WithBgr24();
ctx.Item.CopyPixelDataTo(targetPixelData);
}
///
/// Converts an to a byte array containing raw pixel data.
///
public static byte[] ToBgr24PixelArray(this Image image) {
using var ctx = image.WithBgr24();
return ctx.Item.ToBgr24PixelArray();
}
///
/// Clones a given image into a
/// with correct alpha blending and a given background color.
///
public static Image CloneAlphaBlendedBgr24(this Image image, OmbColor backgroundColor) {
var clonedBgr24 = new Image(image.Width, image.Height);
var color = Color.FromPixel(new Rgb24(
backgroundColor.R,
backgroundColor.G,
backgroundColor.B
));
clonedBgr24.Mutate(x => {
x.BackgroundColor(color);
x.DrawImage(image, 1);
});
return clonedBgr24;
}
///
/// Clones a given image into a
/// with correct alpha blending and black background.
///
public static Image CloneAlphaBlendedBgr24(this Image image) {
var clonedBgr24 = new Image(image.Width, image.Height);
clonedBgr24.Mutate(x => x.DrawImage(image, 1));
return clonedBgr24;
}
///
/// Creates a context with an .
///
///
///
/// If the image already is an this image will be wrapped inside the
/// . If the image is a different pixel format it will be cloned
/// and transformed into an .
///
///
/// Calling on the returned value will never dispose the original
/// but only the implicitly cloned value if any.
///
///
public static ConditionalDisposable> WithBgr24(this Image image) {
return ConstrainedContext.For(image, x => x as Image, x => x.CloneAlphaBlendedBgr24());
}
}
}