正在跳过

时间:2016-01-10 14:25:54

标签: c# arrays bytearray

public byte[] CropImage(byte[] bmp, Rectangle cropSize, int stride)
{ 
    //make a new byte array the size of the area of cropped image
    int totalSize = cropSize.Width * 3 * cropSize.Height;
    int totalLength = bmp.Length;
    int startingPoint = (stride * cropSize.Y) + cropSize.X * 3;
    byte[] croppedImg = new byte[totalSize];

    //for the total size of the old array
    for(int y = 0; y<totalLength; y+= stride)
    {
        //copy a row of pixels from bmp to croppedImg
        Array.Copy(bmp, startingPoint + y, croppedImg, y, cropSize.Width*3);            
    }

    return croppedImg;
}
正在跳过

Array.Copy而不是复制任何内容。

我想也许我犯了一个错误,但即使手动复制每个字节也会做同样的事情。

此函数接收原始BGR图像字节数组[]并根据Rect(x,y,width,height)裁剪它。

最后将裁剪的字节数组返回到main函数。

1 个答案:

答案 0 :(得分:1)

下面

for(int y = 0; y<totalLength; y+= stride)
{
    //copy a row of pixels from bmp to croppedImg
    Array.Copy(bmp, startingPoint + y, croppedImg, y, cropSize.Width*3);            
}

您将y传递给Array.Copy方法参数,该参数应该是destinationIndex,在您的情况下不是这样。

为了避免这些错误,请为变量使用更好的名称(并使用更多变量,它们很便宜)。例如,代码可能就像这样

public byte[] CropImage(byte[] source, Rectangle cropRect, int sourceStride)
{
    int targetStride = cropRect.Width * 3;
    var target = new byte[cropRect.Height * targetStride];
    int sourcePos = cropRect.Y * sourceStride + cropRect.X * 3;
    int targetPos = 0;
    for (int i = 0; i < cropRect.Height; i++)
    {
        Array.Copy(source, sourcePos, target, targetPos, targetStride);
        sourcePos += sourceStride;
        targetPos += targetStride; 
    }
    return target;
}