2017-02-15 71 views
0

我有一張圖片被分成四部分,我想通過RGB改變顏色,但只改變了一半。 1.change當圖片寬度小於256時失敗。 2.my小圖片最大不超過256. 3.每張256 * 256的圖片都是正常的。 4.問題值:r = 0,g = 0,b = 52。c#改變圖片的顏色,但只改變half.by gdi +

private void Adjust(Bitmap pBitmap, params int[] pValues) 
    { 
     BitmapData pBitmapData = pBitmap.LockBits(
      new Rectangle(0, 0, pBitmap.Width, pBitmap.Height), 
      ImageLockMode.ReadWrite, 
      PixelFormat.Format24bppRgb); 

     byte[] pData = new byte[pBitmapData.Stride * pBitmap.Height]; 
     Marshal.Copy(pBitmapData.Scan0, pData, 0, pData.Length); 
     pBitmap.UnlockBits(pBitmapData); 

     int iOffset = pBitmapData.Stride - pBitmapData.Width * 3; 
     int iIndex = 0; 

     for (int i = 0; i < pBitmapData.Height; i++) 
     { 
      for (int j = 0; j < pBitmapData.Width; j++) 
      { 
       for (int k = iIndex; k < iIndex + 3; k++) 
       { 
        pData[k] = Adjust(pData[k], k); 
       } 
       iIndex += 3; 
      } 
      iIndex += iOffset; 
     } 

     Marshal.Copy(pData, 0, pBitmapData.Scan0, pData.Length); 
     //pBitmap.UnlockBits(pBitmapData); 
    } 


protected byte Adjust(byte iValue, int iIndex) 
     { 
      int nColour = 0; 

      switch (iIndex % 3) 
      { 
       case 0: 
        nColour = (int)iValue + m_iBlue; 
        break; 
       case 1: 
        nColour = (int)iValue + m_iGreen; 
        break; 
       case 2: 
        nColour = (int)iValue + m_iRed; 
        break; 
      } 


      return nColour; 
     } 

原始照片,而無需使用問題參數:使用問題參數

enter image description here

原始圖像改變顏色:

enter image description here

+0

我稍微被這裏的標記有關 - GDI +從未在asp.net背景下官方支持。 –

+0

我認爲增加步幅差異會讓它變得混亂。如果iOffset不是3的倍數,那麼您的k%3將不會在第一行之後的0,1,2的順序中。 – Nyerguds

回答

0

你的問題,正如我所說在我的評論中,大步有可能會弄亂%3部分,所以你應該將您正在閱讀的顏色分量作爲單獨的數字傳遞,而不是完整的偏移量。無論如何,該函數不需要或使用該偏移量。

在一個相關的說明中,我認爲最簡單的在字節上迭代圖像的方法就是循環遍歷X和Y,然後計算循環內的真實偏移量。

for (Int32 y = 0; y < pBitmapData.Height; y++) 
{ 
    for (Int32 x = 0; x < pBitmapData.Width; x++) 
    { 
     Int32 offset = y * pBitmapData.Stride + x * 3 
     for (int k = 0; k < 3; k++) 
     { 
      Int32 colOffset = offset + k; 
      pData[colOffset] = Adjust(pData[colOffset], k); 
     } 
    } 
} 

這樣一來,你可以做實際的k值的情況下,交換機爲0/1/2,而不是(偏移+ k)的3%,其中有沒有保證是第一個正確後因爲步長通常將四捨五入爲四個字節的倍數。

最後......做邊界檢查。您正在編輯字節和那些只能去從0到255

protected Byte Adjust(Byte value, Int32 colourComponent) 
{ 
    Int32 newColour = 0; 
    switch (colourComponent) 
    { 
     case 0: 
      newColour = value + m_iBlue; 
      break; 
     case 1: 
      newColour = value + m_iGreen; 
      break; 
     case 2: 
      newColour = value + m_iRed; 
      break; 
    } 
    return (Byte)Math.Max(Math.Min(nColour, 255), 0); 
} 
+0

雖然您的解決方案不可用,但我已用emgucv.thanks解決了它 –

+0

可用?咦? – Nyerguds