Calculating the required buffer size for the WriteableBitmap.WritePixels method

前端 未结 6 2191
甜味超标
甜味超标 2020-12-18 20:19

How do I calculate the required buffer size for the WriteableBitmap.WritePixels method?

I am using the overload taking four parameters, the first is an Int32Rect, th

6条回答
  •  醉梦人生
    2020-12-18 20:22

    Although user Clemens answered the question concerning the buffer size, the questioner was not aware that he calculated the buffer size already correct and the problem was somewhere else.

    While details are given and discussed in comments there is lacking one comprehensive snippet (and complete usage example of .WritePixels (without .CopyPixels) as well). Here it is (I scanned similar questions, but this has been the best place):

    var dpiX = 96;
    
    var writeableBitmap = new WriteableBitmap(width, height, dpiX, dpiX, PixelFormats.Bgra32, null); // Pixelformat of Bgra32 results always in 4 bytes per pixel
    int bytesPerPixel = (writeableBitmap.Format.BitsPerPixel + 7) / 8; // general formula
    int stride = bytesPerPixel * width; // general formula valid for all PixelFormats
    
    byte[] pixelByteArrayOfColors = new byte[stride * height]; // General calculation of buffer size
    
    // The numbers in the array are indices to the used BitmapPalette, 
    //     since we initialized it with null in the writeableBitmap init, they refer directly to RGBA, but only in this case.
    // Choose a light green color for whole bitmap (for not easy to find commented MSDN example with random colors, see https://msdn.microsoft.com/en-us/library/system.windows.media.imaging.writeablebitmap(VS.85).aspx
    for (int pixel = 0; pixel < pixelByteArrayOfColors.Length; pixel += bytesPerPixel)
    {
        pixelByteArrayOfColors[pixel] = 0;        // blue (depends normally on BitmapPalette)
        pixelByteArrayOfColors[pixel + 1] = 255;  // green (depends normally on BitmapPalette)
        pixelByteArrayOfColors[pixel + 2] = 0;    // red (depends normally on BitmapPalette)
        pixelByteArrayOfColors[pixel + 3] = 50;   // alpha (depends normally on BitmapPalette)
    }
    
    writeableBitmap.WritePixels(new Int32Rect(0, 0, width, height), pixelByteArrayOfColors, stride, 0);
    

提交回复
热议问题