【发布时间】:2011-08-07 01:49:05
【问题描述】:
我发现很多人将BitmapSource 转换为Bitmap,但是ImageSource 转换为Bitmap 呢?我正在制作一个成像程序,我需要从Image 元素中显示的图像中提取位图。有谁知道怎么做?
编辑 1:
这是一个将BitmapImage 转换为Bitmap 的函数。请记住在编译器首选项中设置“不安全”选项。
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;
}
接下来是获取BitmapImage:
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();
接下来是转换它:
Bitmap b = new Bitmap(BitmapSourceToBitmap(bi));
【问题讨论】:
-
没有。这太可怕了。
标签: c# image image-processing bitmap