David Horák
David Horák

Reputation: 5565

Get cutout of image data in C#

It possible get cutout of image data. If I know:

byte[] ImageData;
int width;
int height;

Basically I try find how get inner section of image from byte[] source.

For example I have image which is w: 1000px and h: 600px. And I want byte[] middle section 200*200px in byte[].

Upvotes: 1

Views: 601

Answers (2)

Thorsten Dittmar
Thorsten Dittmar

Reputation: 56697

First of all you need to know how many bytes in your array represent one pixel. The following assumes that you have an RGB image with 3 bytes per pixel.

Then, the array-index of the first byte that represents the top-left corner of your cutout is represented as

int i = y * w + x

where y is the y-coordinate of the cutout, w is the width of the entire image and x is the x coordinate of the cutout.

Then, you can do as follows:

// cw: The width of the cutout
// ch: The height of the cutout
// x1/y1: Top-left corner coordinates

byte[] cutout = new byte[cw * ch * 3]; // Byte array that takes the cutout bytes
for (int cy = y1; cy < y2; cy++)
{
    int i = cy * w + x1;
    int dest = (cy - y1) * cw * 3;
    Array.Copy(imagebytes, i, cutout, dest, cw * 3);
}

This iterates from the first to the last row to be cut out. Then, in i, it calculates the index of the first byte of the row in the image that should be cutout. In dest it calculates the index in cutout to which the bytes should be copied.

After that it copies the bytes for the current row to be cut out into cutout at the specified position.

I have not tested this code, really, but something like that should work. Also, please note that there's currently no range checking - you need to make sure that the location and dimensions of the cutout are really within the bounds of the image.

Upvotes: 2

Preet Sangha
Preet Sangha

Reputation: 65506

If you can convert it to an an image first, you can use this code I found on Bytes.Com

The following code works for me. It loads a .gif, draws the 30 x 30 section of the gif into an offscreen bitmap, and then draws the scaled image into a picturebox.

System.Drawing.Image img=... create the image from the bye array ....
Graphics g1 = pictureBox1.CreateGraphics();
g1.DrawImage(img, 0, 0, img.Width, img.Height);
g1.Dispose();

Graphics g3 = Graphics.FromImage(bmp);
g3.DrawImageUnscaled(img, 0, 0, bmp.Width, bmp.Height);

Graphics g2 = pictureBox2.CreateGraphics();
g2.DrawImageUnscaled(bmp, 0, 0, bmp.Width, bmp.Height);
g2.Dispose();

g3.Dispose();
img.Dispose();

You can use this question to turn your byte[] into an image : Convert a Byte array to Image in c# after modifying the array

Upvotes: 0

Related Questions