2012-12-13 42 views
1

可能会剪切掉图像数据。 如果我知道:获取C中图像数据的剪切图像

byte[] ImageData; 
int width; 
int height; 

基本上我试图找到如何从byte[]源获取图像的内部部分。

例如我有图像,它是w:1000px和h:600px。我想byte[]中段200 * 200px在byte[]

回答

2

首先,你需要知道你的数组中有多少字节代表一个像素。以下假设您有一个每像素3个字节的RGB图像。

然后,在第一字节的代表您切口的左上角的阵列索引被表示为

int i = y * w + x 

其中y是切口的y - 协调,w是的宽度整个图像和x是切口的x坐标。

然后,你可以做如下:

// 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); 
} 

从第一个到最后一行这个迭代被切出。然后,在i中,它计算应该剪切的图像中行的第一个字节的索引。在dest它计算应在其中复制字节的cutout中的索引。

之后,它将要剪切的当前行的字节复制到指定位置的cutout

我还没有测试过这个代码,真的,但类似的东西应该工作。另外请注意,目前没有范围检查 - 您需要确保切口的位置和尺寸确实在图像的范围内。

+0

谢谢,这绝对是我想要的 –

0

如果你可以把它的图像首先转换为,您可以使用此代码我在Bytes.Com

下面的代码对我的作品中。它加载一个.gif,将gif的30 x 30 部分绘制到离屏位图中,然后将缩放的 图像绘制到图片框中。

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(); 

你可以用这个问题把你的byte []成图像:Convert a Byte array to Image in c# after modifying the array所有的

+0

谢谢你的回应,不幸的是我试图不使用System.Drawing,所以我接受Thorsten-dittmar解决方案,因为它只使用低级别的.net库。但是再次感谢 –