You are using a raw pointer there. Where does that come from? It is advised to use managed arrays, unless you can be 100% sure that that pointer will remain valid.
If it comes from a LockBits
operation on another image, it will not remain valid; it will stop being reliable from the moment the other image is unlocked.
If you are planning to clone or edit an 8bpp image, it is much safer to copy the contents of the images you're manipulating into normal managed Byte[]
arrays, using LockBits
and Marshal.Copy
, and to copy them back into Bitmap
objects the same way, rather than using pointers directly.
These pieces of code should set you on your way:
Get the backing byte array from an image:
/// <summary>
/// Gets the raw bytes from an image.
/// </summary>
/// <param name="sourceImage">The image to get the bytes from.</param>
/// <param name="stride">Stride of the retrieved image data.</param>
/// <returns>The raw bytes of the image</returns>
public static Byte[] GetImageData(Bitmap sourceImage, out Int32 stride)
{
BitmapData sourceData = sourceImage.LockBits(new Rectangle(0, 0, sourceImage.Width, sourceImage.Height), ImageLockMode.ReadOnly, sourceImage.PixelFormat);
stride = sourceData.Stride;
Byte[] data = new Byte[stride * sourceImage.Height];
Marshal.Copy(sourceData.Scan0, data, 0, data.Length);
sourceImage.UnlockBits(sourceData);
return data;
}
Create an image from a byte array: (rather than from a pointer)
And, combined and optimised:
Make a deep clone of an image to load it without any linked resources
Note, as for your disposing... you should never dispose an image still linked to the UI, since the next repaint of the UI will attempt to use the disposed image, which will inevitably cause a crash. The correct way to do this is to store the image reference in a variable, then make it null on the UI, and then dispose it:
if (Picturebox1 != null && Picturebox1.Image != null)
{
Image img = Picturebox1.Image;
Picturebox1.Image = null;
img.Dispose();
}