我想知道是否可以將圖像文件直接加載到預分配的內存,而不需要爲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);
}
}
希望有人可以幫助我這個。提前致謝!
爲什麼你想這樣做? – Yogee 2015-02-23 14:15:50
因爲分配始終成本很高。對於操作系統和GC。 – Andreas 2015-02-23 14:17:18
首先:你的情況分配成本是多少?我想這不會是瓶頸。第二:BitmapImage是一次性的,你應該在GC之前手動處理它。 – Yogee 2015-02-23 14:20:15