使用BitmapData和Lock和UnlockBits taken from the MSDN编辑位图的方法似乎在具有不同大小的位图上的工作方式非常不同。它只在PixelFormat.Format24bppRgb上执行此操作并且更改它似乎可以修复它,但我想知道发生了什么。
以下是参考方法:
private void LockUnlockBitsExample(PaintEventArgs e)
{
// Create a new bitmap.
Bitmap bmp = new Bitmap("c:\\fakePhoto.jpg");
// Lock the bitmap's bits.
Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height);
System.Drawing.Imaging.BitmapData bmpData =
bmp.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite,
bmp.PixelFormat);
// Get the address of the first line.
IntPtr ptr = bmpData.Scan0;
// Declare an array to hold the bytes of the bitmap.
int bytes = Math.Abs(bmpData.Stride) * bmp.Height;
byte[] rgbValues = new byte[bytes];
// Copy the RGB values into the array.
System.Runtime.InteropServices.Marshal.Copy(ptr, rgbValues, 0, bytes);
// Set every third value to 255. A 24bpp bitmap will look red.
for (int counter = 2; counter < rgbValues.Length; counter += 3)
rgbValues[counter] = 255;
// Copy the RGB values back to the bitmap
System.Runtime.InteropServices.Marshal.Copy(rgbValues, 0, ptr, bytes);
// Unlock the bits.
bmp.UnlockBits(bmpData);
// Draw the modified image.
e.Graphics.DrawImage(bmp, 0, 150);
}
它适用于Bitmap(200,200)或Bitmap(200,250)。但是当它用于Bitmap(50,50)或大多数其他尺寸时,它会变得非常疯狂......
for (int counter = 10; counter + 10 < rgbValues.Length; counter += n)
rgbValues[counter] = 255;
//Doesn't work for any number put for n from 2 to 10
//I also limited it from beginning and end just to try
//if it's not changing some crucial value in the bytes
//(I know it's a nonsense but I tried)
有人可以解释为什么会这样吗?怎么能解决这个问题呢? (除了改变格式)
注意:我并不热衷于这种格式,但我想知道实际发生了什么。