2015-02-23 64 views
0

我想知道是否可以將圖像文件直接加載到預分配的內存,而不需要爲bitmapimage本身分配新的內存。 我寫了一個示例類來演示我想要做什麼。如何在.net中加載圖像時使用預先分配的內存

public class PreAllocatedImageLoader 
    { 
     private readonly int _width; 
     private readonly int _height; 
     private readonly int _stride; 
     private readonly IntPtr _imageData; 

     public PreAllocatedImageLoader(int width, int height, PixelFormat pixelFormat) 
     { 
      _width = width; 
      _height = height; 
      _stride = width * ((pixelFormat.BitsPerPixel + 7)/8); 
      _imageData = Marshal.AllocHGlobal(height * _stride); 
     } 

     public void LoadFromFile(string filePath) 
     { 
      // Oh nooo, we allocate memory here 
      var newAllocatedImage = new BitmapImage(new Uri(filePath)); 
      // Copy the pixels in the preallocated memory 
      newAllocatedImage.CopyPixels(new Int32Rect(0, 0, _width, _height), _imageData, _height * _stride, _stride); 
     } 
    } 

希望有人可以幫助我這個。提前致謝!

+1

爲什麼你想這樣做? – Yogee 2015-02-23 14:15:50

+0

因爲分配始終成本很高。對於操作系統和GC。 – Andreas 2015-02-23 14:17:18

+0

首先:你的情況分配成本是多少?我想這不會是瓶頸。第二:BitmapImage是一次性的,你應該在GC之前手動處理它。 – Yogee 2015-02-23 14:20:15

回答

1

對於使用WPF的圖像不可能使用自分配的內存。按照要求回答你的問題。你一直堅持認爲這是你想要的,但沒有辦法做到這一點。

What you should do instead is make sure that memory is released when no longer needed.不幸的是,這並不像人們希望的那樣直截了當。

+0

我不限於WPF!我發現這個https://msdn.microsoft.com/en-us/library/aa288474(v=vs.71)。aspx#vcwlkunsafecode_readfileexample。我會在接下來的幾天測試它 – Andreas 2015-02-24 09:29:22

+0

XY問題。你想做什麼?如果你想做圖像處理考慮使用System.Drawing。它允許精確的內存管理。 – usr 2015-02-24 09:55:17

+0

似乎可以用「unsafe bool ReadFile」方法將文件讀入預分配的數據緩衝區。但是,也許你的答案是正確的,這是不可能的 – Andreas 2015-02-24 11:18:05

0

我不認爲這是BitmapImage類支持。它只能被初始化一次,所以你不能重新使用它,它不支持明確指定內存位置。

我想你可以嘗試通過製作一個流源(memoryStream)並從中初始化你的BitmapImage來避開這個問題,因爲它們對生命週期有更多的有限控制。

我會不是在你的代碼中使用IntPtr的周圍,除非絕對必要,因爲你在那裏有危險的水。任何使用任何非託管資源的東西都必須實現IDisposable(你不是),並且在你自己之後進行適當的清理變得更加困難。

相關問題