我發現大量人將BitmapSource
轉換爲Bitmap
,但ImageSource
轉換爲Bitmap
?我正在製作一個成像程序,我需要從Image
元素中顯示的圖像中提取位圖。有誰知道如何做到這一點?C# - 將WPF Image.source轉換爲System.Drawing.Bitmap
EDIT 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));
請注意,在內部,這個'Bitmap'的構造函數調用'GdipCreateBitmapFromScan0',它希望用戶在不再需要時釋放內存...... – Cameron 2014-03-17 13:45:20
@Cameron,好點。我編輯了我的答案,將其考慮在內。 – 2014-03-17 15:37:32
不幸的是,內存不能被釋放,直到System.Drawing.Bitmap被處置(我找不到任何文檔,但在互操作性應用程序中試用後,我的圖像只顯示正確,如果我之後免費,所以它看起來不像是在內部複製數據)。另外,[GDI文檔](http://www.jose.it-berater.org/gdiplus/reference/flatapi/bitmap/gdipcreatebitmapfromscan0.htm)似乎要求跨度是4的倍數;所以'(srs.Format.BitsPerPixel + 7)/ 8'應該是'(srs.Format.BitsPerPixel + 31)/ 32 * 8',我相信。 – Cameron 2014-03-20 20:34:40