2025-06-12 14:34:51 +01:00

42 lines
1.2 KiB
C#

using System.Drawing;
using System.IO;
using System.Windows.Media.Imaging;
namespace ShadowStream.Modules;
public class BitmapConversions
{
public static BitmapImage BitmapToBitmapImage(System.Drawing.Bitmap bitmap)
{
using (var memory = new System.IO.MemoryStream())
{
bitmap.Save(memory, System.Drawing.Imaging.ImageFormat.Png);
memory.Position = 0;
var bitmapImage = new BitmapImage();
bitmapImage.BeginInit();
bitmapImage.StreamSource = memory;
bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
bitmapImage.EndInit();
bitmapImage.Freeze(); // Optional: for thread safety
return bitmapImage;
}
}
public static Bitmap BitmapImageToBitmap(BitmapImage bitmapImage)
{
using (MemoryStream ms = new MemoryStream())
{
// Encode BitmapImage to stream (e.g., PNG)
BitmapEncoder encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(bitmapImage));
encoder.Save(ms);
ms.Seek(0, SeekOrigin.Begin); // Reset stream position
// Create Bitmap from stream
return new Bitmap(ms);
}
}
}