3 回答

TA貢獻(xiàn)1780條經(jīng)驗(yàn) 獲得超5個(gè)贊
每當(dāng)處理非托管句柄時(shí),使用“安全句柄”包裝器是個(gè)好主意:
public class SafeHBitmapHandle : SafeHandleZeroOrMinusOneIsInvalid{ [SecurityCritical] public SafeHBitmapHandle(IntPtr preexistingHandle, bool ownsHandle) : base(ownsHandle) { SetHandle(preexistingHandle); } protected override bool ReleaseHandle() { return GdiNative.DeleteObject(handle) > 0; }}
只要你展示一個(gè)句柄就構(gòu)造一個(gè)(理想情況下你的API永遠(yuǎn)不會(huì)暴露IntPtr,它們總是返回安全句柄):
IntPtr hbitmap = bitmap.GetHbitmap();var handle = new SafeHBitmapHandle(hbitmap , true);
并像這樣使用它:
using (handle){ ... Imaging.CreateBitmapSourceFromHBitmap(handle.DangerousGetHandle(), ...)}
SafeHandle基礎(chǔ)為您提供自動(dòng)一次性/終結(jié)器模式,您需要做的就是覆蓋ReleaseHandle方法。

TA貢獻(xiàn)1830條經(jīng)驗(yàn) 獲得超9個(gè)贊
我有相同的要求和問題(內(nèi)存泄漏)。我實(shí)施了標(biāo)記為答案的相同解決方案。但是雖然解決方案有效,但它對(duì)性能造成了不可接受的打擊。在i7上運(yùn)行,我的測(cè)試應(yīng)用程序看到了穩(wěn)定的30-40%CPU,200-400MB RAM增加,垃圾收集器幾乎每毫秒運(yùn)行一次。
由于我正在進(jìn)行視頻處理,因此我需要更好的性能。我想出了以下內(nèi)容,以為我會(huì)分享。
可重用的全局對(duì)象
//set up your Bitmap and WritableBitmap as you see fitBitmap colorBitmap = new Bitmap(..);WriteableBitmap colorWB = new WriteableBitmap(..);//choose appropriate bytes as per your pixel format, I'll cheat here an just pick 4int bytesPerPixel = 4;//rectangles will be used to identify what bits changeRectangle colorBitmapRectangle = new Rectangle(0, 0, colorBitmap.Width, colorBitmap.Height);Int32Rect colorBitmapInt32Rect = new Int32Rect(0, 0, colorWB.PixelWidth, colorWB.PixelHeight);
轉(zhuǎn)換代碼
private void ConvertBitmapToWritableBitmap(){ BitmapData data = colorBitmap.LockBits(colorBitmapRectangle, ImageLockMode.WriteOnly, colorBitmap.PixelFormat); colorWB.WritePixels(colorBitmapInt32Rect, data.Scan0, data.Width * data.Height * bytesPerPixel, data.Stride); colorBitmap.UnlockBits(data); }
實(shí)施例
//do stuff to your bitmapConvertBitmapToWritableBitmap();Image.Source = colorWB;
結(jié)果是穩(wěn)定的10-13%CPU,70-150MB RAM,垃圾收集器在6分鐘運(yùn)行中僅運(yùn)行兩次。
- 3 回答
- 0 關(guān)注
- 1352 瀏覽
添加回答
舉報(bào)