wpf icon indicating copy to clipboard operation
wpf copied to clipboard

System.OverflowException in WriteableBitmap.WritePixels

Open petsuter opened this issue 7 months ago • 11 comments

Description

WriteableBitmap can not exceed 4 GB I think (WriteableBitmap constructor fails) but even for sizes below 4 GB (but above 2GB) there are overflow exceptions in WriteableBitmap.WritePixels, even when only writing a tiny amount of data.

Reproduction Steps

                int size = 30000;
                int tileSize = 100;
                int channels = 4;
                var pix = new byte[tileSize * tileSize * channels];
                var bitmap = new WriteableBitmap(size, size, 96, 96, PixelFormats.Pbgra32, null);
                bitmap.WritePixels(new Int32Rect(0, 0, tileSize, tileSize),
                      pix, tileSize * channels, size-tileSize, size-tileSize);

Expected behavior

No exception. (Or if >2GB is considered unsupported, the constructor should already fail?)

Actual behavior

Exception:

System.OverflowException
  HResult=0x80131516
  Message=Arithmetic operation resulted in an overflow.
  Source=PresentationCore
  StackTrace:
   at System.Windows.Media.Imaging.WriteableBitmap.WritePixelsImpl(Int32Rect sourceRect, IntPtr sourceBuffer, Int32 sourceBufferSize, Int32 sourceBufferStride, Int32 destinationX, Int32 destinationY, Boolean backwardsCompat) in System.Windows.Media.Imaging\WriteableBitmap.cs:line 583
   at System.Windows.Media.Imaging.WriteableBitmap.WritePixels(Int32Rect sourceRect, Array sourceBuffer, Int32 sourceBufferStride, Int32 destinationX, Int32 destinationY) in System.Windows.Media.Imaging\WriteableBitmap.cs:line 271
   at Program.Main() in Program.cs:line 15

Regression?

I don't think so.

Known Workarounds

None

Impact

Unknown

Configuration

.NET 8, Windows 11, x64. I don't think this is specific.

Other information

None.

Maybe uint should be used somewhere instead of int in the internal offset calculations?

petsuter avatar Jul 22 '24 10:07 petsuter