在 .net 中加载图像时如何使用预分配内存

How do I use pre-allocated memory when loading a Image in .net

我想知道是否可以在不对位图图像本身进行新分配的情况下将图像文件直接加载到预分配的内存中。 我写了一个示例 class 来演示我想做什么。

  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);
        }
    }

希望有人能帮我解决这个问题。提前致谢!

我认为 BitmapImage 不支持此功能 class。它只能初始化一次,所以你不能重复使用它,它不支持显式指定内存位置。

我想您可以尝试通过创建一个流源 (memoryStream) 并从中初始化您的 BitmapImage 来回避这个问题,因为它们对生命周期的控制更有限。

除非绝对必要,否则我会不会在您的代码中使用 IntPtr,因为您正处于危险的水中。任何具有任何非托管资源的东西都必须实现 IDisposable(你不是),并且在你自己之后正确清理变得更加困难。

无法使用 WPF 为图像使用自行分配的内存。这会按要求回答您的问题。你在评论里一直很坚持说这是你想要的但是没有办法做到。

What you should do instead is make sure that memory is released when no longer needed. 不幸的是,这并不像人们希望的那样直截了当。