C # - Converter WPF Image.source em um System.Drawing.Bitmap
Encontrei muitas pessoas convertendo umBitmapSource
para umBitmap
, mas eImageSource
paraBitmap
? Estou criando um programa de criação de imagens e preciso extrair bitmaps da imagem exibida noImage
elemento. Alguém sabe como fazer isso
EDIT 1:
Esta é uma função para converter oBitmapImage
para umBitmap
. Lembre-se de definir a opção 'não segura' nas preferências do compilado
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 agora é obter umBitmapImage
:
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 é convertê-lo:
Bitmap b = new Bitmap(BitmapSourceToBitmap(bi));