dotnet / dotnet/dotnet-api-docs

Bitmap(Int32, Int32, Int32, PixelFormat, IntPtr) ctor: Unclear scan0 parameter explanation and possibly incorrect code example

Open
#7,022 2 comments 0 reactions 0 assignees View on GitHub
area-System.Drawing Pri3 untriaged
Dominant language
C#
Stars
949
Forks
1.7k
Avg merge
3d 27m
Merged PRs (30d)
49

Description

In the documentation for the [System.Drawing.Bitmap(Int32, Int32, Int32, PixelFormat, IntPtr) constructor](https://docs.microsoft.com/en-us/dotnet/api/system.drawing.bitmap.-ctor?view=net-5.0#System_Drawing_Bitmap__ctor_System_Int32_System_Int32_System_Int32_System_Drawing_Imaging_PixelFormat_System_IntPtr_), it is not explained clearly whether the newly created bitmap will need the data at the location pointed at by _scan0_ during its lifetime, or whether it makes a copy of the data buffer.

The remarks section only explains somewhat nebulously

> The caller is responsible for allocating and freeing the block of memory specified by the scan0 parameter. However, the memory > should not be released until the related Bitmap is released.

strongly indicating that the newly created Bitmap instance will not make a copy of the byte data, but relies on the continued existence of the given data buffer pointed at by _scan0_.

However, the provided code example for this _Bitmap_ ctor gives a contradictory impression. The code example, with unnecessary pieces removed for brevity:
```c#
// Retrieve the bitmap data from the bitmap.
System.Drawing.Imaging.BitmapData bmpData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height),
ImageLockMode.ReadOnly, bmp.PixelFormat);

//Create a new bitmap.
Bitmap newBitmap = new Bitmap(200, 200, bmpData.Stride, bmp.PixelFormat, bmpData.Scan0);

bmp.UnlockBits(bmpData);

// Draw the new bitmap.
e.Graphics.DrawImage(newBitmap, 10, 10);
```
The pointer passed to the _scan0_ parameter of the _Bitmap_ ctor is pointing at the data of another locked bitmap. And the new Bitmap instance is being drawn _after_ the other bitmap has been unlocked, thus contradicting the explanation in the remarks section.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.