Added ToBitmap nad ToBmp extensions for image

This commit is contained in:
Darth Affe 2024-07-14 22:51:10 +02:00
parent 6f762f7ad6
commit 0a731b5ca4

View File

@ -6,9 +6,62 @@ namespace HPPH.System.Drawing;
public static class ImageExtension public static class ImageExtension
{ {
public static Bitmap ToBitmap(this IImage image) [SupportedOSPlatform("windows")]
public static unsafe Bitmap ToBitmap(this IImage image)
{ {
throw new NotImplementedException(); switch (image.ColorFormat.BytesPerPixel)
{
case 3:
{
Bitmap bitmap = new(image.Width, image.Height, PixelFormat.Format24bppRgb);
BitmapData bmpData = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.WriteOnly, bitmap.PixelFormat);
IImage<ColorRGB> convertedImage = image.ConvertTo<ColorRGB>();
nint ptr = bmpData.Scan0;
foreach (ImageRow<ColorRGB> row in convertedImage.Rows)
{
row.CopyTo(new Span<byte>((void*)ptr, bmpData.Stride));
ptr += bmpData.Stride;
}
bitmap.UnlockBits(bmpData);
return bitmap;
}
case 4:
{
Bitmap bitmap = new(image.Width, image.Height, PixelFormat.Format32bppArgb);
BitmapData bmpData = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.WriteOnly, bitmap.PixelFormat);
IImage<ColorRGBA> convertedImage = image.ConvertTo<ColorRGBA>();
nint ptr = bmpData.Scan0;
foreach (ImageRow<ColorRGBA> row in convertedImage.Rows)
{
row.CopyTo(new Span<byte>((void*)ptr, bmpData.Stride));
ptr += bmpData.Stride;
}
bitmap.UnlockBits(bmpData);
return bitmap;
}
default:
throw new NotSupportedException($"Unsupported color format '{image.ColorFormat}'.");
}
}
[SupportedOSPlatform("windows")]
public static byte[] ToPng(this IImage image)
{
using Bitmap bitmap = ToBitmap(image);
using MemoryStream ms = new();
bitmap.Save(ms, ImageFormat.Png);
return ms.ToArray();
} }
[SupportedOSPlatform("windows")] [SupportedOSPlatform("windows")]