简体   繁体   中英

C# - How do I create a new byte array from a portion of a larger one

I'm rather new to coding so I'm not sure if this is a really obvious question or not. What I have is an ordered list of bytes that represent pixels and depth data related to those pixels, so when returned into a box they create an image. What I'm trying to do is isolate a smaller rectangle of those bytes into a new byte array.

So basically I want to skip a large amount of the bytes at the start of the array (the ones completely above the smaller rectangle section), as well as the first lot on the left of it, then add one row of the length of the smaller box to the new array, then skip the ones on the right of the box, skip the left side on the next line down, add the length, skip the right and repeat it all until I reach the end of the box.

I really hope that bad explanation makes sense to someone. I have no idea how to go about doing this. Any help would be really appreciated!

Thanks!

The simplest option is probably to create a byte array of the right size, then use Array.Copy or Buffer.BlockCopy - multiple times, by the sounds of it.

I suspect you'll need to call the copy method once per row, working out where in the source data the relevant part of the row starts, where in the target data the relevant part of the row starts. I'll leave the rest to you for the moment now you've got the basic idea - but feel free to ask for more clarification. Don't forget (in your calculations) that the "target" row number won't be equal to the "source" row number! (I suspect it's easiest to loop over the target row numbers, and add an offset...)

I think it would look something like this:

const int numberOfBytesPerPixel = ...;

// input: original data
int originalWidth = ...;
int originalHeight = ...;
byte[] original = ...; // should have the correct size and contain the data

// input: desired position and size for cropping rectangle
int cropOffsetToTheRight = ...;
int cropOffsetDown = ...;
int cropWidth = ...;
int cropHeight = ...;

// get the rectangle:
byte[] crop = new byte[numberOfBytesPerPixel * cropWidth * cropHeight];
for (int rowNumber = 0; rowNumber < cropHeight; ++rowNumber)
{
    Array.Copy(
        original,
        numberOfBytesPerPixel * ((cropOffsetDown + rowNumber) * originalWidth + cropOffsetToTheRight),
        crop,
        numberOfBytesPerPixel * rowNumber,
        numberOfBytesPerPixel * cropWidth
        );
}

Here's the doc for the overload of Array.Copy used .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM