C # - Convierte WPF Image.source en un System.Drawing.Bitmap
He encontrado un montón de personas convirtiendo unBitmapSource
a unBitmap
, pero que pasaImageSource
aBitmap
? Estoy haciendo un programa de imágenes y necesito extraer mapas de bits de la imagen que se muestra enImage
elemento. ¿Alguien sabe como hacer esto
EDIT 1:
Esta es una función para convertir elBitmapImage
a unBitmap
. Recuerde configurar la opción 'insegura' en las preferencias del compilador.
public static System.Drawing.Bitmap BitmapSourceToBitmap(BitmapSource srs)
{
System.Drawing.Bitmap btm = null;
int width = srs.PixelWidth;
int height = srs.PixelHeight;
int stride = width * ((srs.Format.BitsPerPixel + 7) / 8);
byte[] bits = new byte[height * stride];
srs.CopyPixels(bits, stride, 0);
unsafe
{
fixed (byte* pB = bits)
{
IntPtr ptr = new IntPtr(pB);
btm = new System.Drawing.Bitmap(width, height, stride, System.Drawing.Imaging.PixelFormat.Format1bppIndexed, ptr);
}
}
return btm;
}
Next ahora es obtener unBitmapImage
:
RenderTargetBitmap targetBitmap = new RenderTargetBitmap(
(int)inkCanvas1.ActualWidth,
(int)inkCanvas1.ActualHeight,
96d, 96d,
PixelFormats.Default);
targetBitmap.Render(inkCanvas1);
MemoryStream mse = new MemoryStream();
System.Windows.Media.Imaging.BmpBitmapEncoder mem = new BmpBitmapEncoder();
mem.Frames.Add(BitmapFrame.Create(targetBitmap));
mem.Save(mse);
mse.Position = 0;
BitmapImage bi = new BitmapImage();
bi.BeginInit();
bi.StreamSource = mse;
bi.EndInit();
Next es convertirlo:
Bitmap b = new Bitmap(BitmapSourceToBitmap(bi));