2012-12-13 23 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庫。但是再次感謝 –