2016-11-16 31 views
0

我對位圖不是很熟悉,我需要將FrameworkElement(特定Grid)保存爲位圖並將其複製到緩衝區。問題是我需要將它保存爲Rgba格式,而不是Pgrba,這在RenderTargetBitmap中不受支持。相關的代碼在這裏:格式爲rgba32的RenderTargetBitmap

_targetBitmap = new RenderTargetBitmap(xres, yres, 96, 96, PixelFormats.Pbgra32); 
_targetBitmap.Clear(); 
// Child is grid 
_targetBitmap.Render(Child); 
// copy the pixels into the buffer 
_targetBitmap.CopyPixels(new Int32Rect(0, 0, xres, yres), bufferPtr, _bufferSize, _stride); 

我試過使用WriteableBitmap,但我沒有如何呈現子。有什麼建議麼?

+0

顯然,WPF根本不支持Rgba32。那麼WriteableBitmap應該如何幫助? – Clemens

+0

哦,我以爲是的。我的錯。 – Korhak

回答

1

CopyPixels函數已經可以直接訪問像素數據,所以您只需要在格式之間進行轉換。在這種情況下,您需要調換通道順序並撤銷alpha值的預乘。

注意:此代碼假定您的bufferPtr是一個字節數組或字節指針。

for (int y = 0; y < yres; y++) 
{ 
    for (int x = 0; x < xres; x++) 
    { 
     // Calculate array offset for this pixel 
     int offset = y * _stride + x * 4; 

     // Extract individual color channels from pixel value 
     int pb = bufferPtr[offset]; 
     int pg = bufferPtr[offset + 1]; 
     int pr = bufferPtr[offset + 2]; 
     int alpha = bufferPtr[offset + 3]; 

     // Remove premultiplication 
     int r = 0, g = 0, b = 0; 
     if (alpha > 0) 
     { 
      r = pr * 255/alpha; 
      g = pg * 255/alpha; 
      b = pb * 255/alpha; 
     } 

     // Write color channels in desired order 
     bufferPtr[offset] = (byte)r; 
     bufferPtr[offset + 1] = (byte)g; 
     bufferPtr[offset + 2] = (byte)b; 
     bufferPtr[offset + 3] = (byte)alpha; 
    } 
}