如何将一个IntPtr分配给其他IntPtr

时间:2012-08-21 18:46:58

标签: .net bitmapdata intptr

我正在尝试使用BitmapData类?并将IntPtr值分配给BitmapData.Scan0属性有一些问题。这是我的代码:

var data = bmp.LockBits(new rectangle(Point.Empty, bmp.Size), ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb);
data.Scan0 = rh.data.Scan0HGlobal;
bmp.UnlockBits(data);

但是,解锁图像后,它不会改变。为什么?在调试模式下,我看到data.Scan0已更改为rh.data.Scan0HGlobal值。在rh.data.Scan0HGlobal中,我有指向包含像素原始数据的内存的指针。

2 个答案:

答案 0 :(得分:4)

嗯,Scan0属性设置器不是私有的,有点可悲。但是,是的,这没有任何作用。您需要自己复制字节以更改图像。使用Marshal.Copy()复制pinvoke memcpy()的byte []辅助数组。

答案 1 :(得分:1)

这是你应该怎么做的:

// Lock image bits.
// Also note that you probably should be using bmp.PixelFormat instead of
// PixelFormat.Format32bppArgb (if you are not sure what the image pixel
// format is).
var bmpData = bmp.LockBits(new Rectangle(Point.Empty, bmp.Size),
    ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb);

// This is total number of bytes in bmp.
int byteCount = bmpData.Stride * bmp.Height;
// And this is where image data will be stored.
byte[] rgbData = new byte[byteCount];

// Copy bytes from image to temporary byte array rgbData.
System.Runtime.InteropServices.Marshal.Copy(
    bmpData.Scan0, rgbData, 0, byteCount);    

// TODO: Work with image data (now in rgbData), perform calculations,
// set bytes, etc.
// If this operation is time consuming, perhaps you should unlock bits
// before doing it.
// Do remember that you have to lock them again before copying data
// back to the image.

// Copy bytes from rgbData back to the image.
System.Runtime.InteropServices.Marshal.Copy(
   rgbData, 0, bmpData.Scan0, byteCount);
// Unlock image bits.
image.UnlockBits(bmpData);

// Save modified image, or do whatever you want with it.

希望它有所帮助!