1
我試圖用另一張圖像替換圖像塊,但我在Marshal.Copy(rgbValues, startIndx, desPtr, bytes)
上得到System.ArgumentOutOfRangeException
,就在我進入第二行時。我不明白爲什麼,因爲我是這個圖像處理的新手。這裏是我的代碼:如何用另一個圖像替換圖像中的塊?
public static void ReplaceImageBlock(Bitmap src, Bitmap des, int x, int y, int xParts, int yParts)
{
var srcRec = new Rectangle(0, 0, src.Width, src.Height);
BitmapData srcData = src.LockBits(srcRec,
ImageLockMode.ReadOnly, src.PixelFormat);
var desRec = new Rectangle(x, y, src.Width, src.Height);
BitmapData desData = des.LockBits(desRec, ImageLockMode.WriteOnly, des.PixelFormat);
int srcStride = srcData.Stride;
IntPtr srcPtr = srcData.Scan0;
int desStride = desData.Stride;
IntPtr desPtr = desData.Scan0;
int bytes = 3 * xParts;
var rgbIndex = 0;
//actual pixel values
int width = 3 * xParts; //3 bytes by xParts
int height = yParts;
var rgbValues = new byte[bytes];
// Populate rgbValues with src image
unsafe
{
byte* p = (byte*)(void*)srcPtr;
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
int index = (i * srcStride) + j;
rgbValues[rgbIndex++] = p[index];
}
rgbIndex = 0; // reset index
var startIndx = (i * desStride) + x;
Marshal.Copy(rgbValues, startIndx, desPtr, bytes);//copy to destination block
}
}
}
'startIndx'可以被計算錯了要簡單得多? – TW80000
你使用3個字節的像素,但你確定位圖格式是RGB而不是RGBA? – Aybe
@Aybe,我該如何檢查格式?我的圖像屬性說比特深度是24. @TW我在'startIndex'上會做錯什麼? –