As described in my other answer, the best way to solve this is to directly access the bitmap image data. BitmapImage inherits from BitmapSource. BitmapSource is great for this, and also works with WPF binding.
BitmapSource , WPF ( MVVM). BitmapSource. / BitmapSource, WPF . "Bitmap", . . (, 4- 30 .. , .)
. :
unsafe {
byte* imgBytePtr = (byte*)myBitmap.ImageData;
Int32* imgInt32Ptr = (Int32*)myBitmap.ImageData;
int height = (int)myBitmap.BitmapSource.Height;
int width = (int)myBitmap.BitmapSource.Width;
int bpp = myBitmap.BytesPerPixel;
for (int x = 0; x < height; x++)
{
for (int y = 0; y < width; y++)
{
int bytePos = x * (width * bpp) + (y * bpp);
byte R = imgBytePtr[bytePos + 0];
byte B = imgBytePtr[bytePos + 1];
byte G = imgBytePtr[bytePos + 2];
byte A = imgBytePtr[bytePos + 3];
int intPos = x * width + y;
int intColor = imgIntPtr[intPos];
imgBytePtr[bytePos + 1] = 0;
imgIntPtr[intPos] = imgIntPtr[intPos] & 0xFF00FFFF;
}
}
}
BitmapSource, BitmapImage, , .
public class Bitmap : IDisposable
{
[DllImport("kernel32.dll", SetLastError = true)]
static extern IntPtr CreateFileMapping(IntPtr hFile, IntPtr lpFileMappingAttributes, uint flProtect, uint dwMaximumSizeHigh, uint dwMaximumSizeLow, string lpName);
[DllImport("kernel32.dll", SetLastError = true)]
static extern IntPtr MapViewOfFile(IntPtr hFileMappingObject, uint dwDesiredAccess, uint dwFileOffsetHigh, uint dwFileOffsetLow, uint dwNumberOfBytesToMap);
[DllImport("kernel32.dll", SetLastError = true)]
static extern bool UnmapViewOfFile(IntPtr hMap);
[DllImport("kernel32.dll", SetLastError = true)]
static extern bool CloseHandle(IntPtr hHandle);
private IntPtr _section = IntPtr.Zero;
public IntPtr ImageData { get; private set; }
public InteropBitmap BitmapSource { get; private set; }
public int BytesPerPixel = 3;
public Bitmap(int width, int height, PixelFormat pixelFormat)
{
BytesPerPixel = pixelFormat.BitsPerPixel / 8;
uint imageSize = (uint)width * (uint)height * (uint)BytesPerPixel;
_section = CreateFileMapping(new IntPtr(-1), IntPtr.Zero, 0x04, 0, imageSize, null);
ImageData = MapViewOfFile(_section, 0xF001F, 0, 0, imageSize);
BitmapSource = Imaging.CreateBitmapSourceFromMemorySection(_section, width, height, pixelFormat, width * BytesPerPixel, 0) as InteropBitmap;
}
public void Invalidate()
{
BitmapSource.Invalidate();
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected void Dispose(bool disposing)
{
if (disposing)
{
}
if (ImageData != IntPtr.Zero)
{
UnmapViewOfFile(ImageData);
ImageData = IntPtr.Zero;
}
if (_section != IntPtr.Zero)
{
CloseHandle(_section);
_section = IntPtr.Zero;
}
}
}