I am wondering if it is possible to load an Image-File directly to the preallocated memory WITHOUT a new allocation for the bitmapimage itself. I wrote a sample class to demonstrate what I want to do.
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);
}
}
Hopefully someone can help me with this. Thanks in advance!