C# System.Drawing.Image.get_Width() throws exception on WinForms form is maximized

浪尽此生 提交于 2020-01-16 21:58:09

问题


I writing Windows Forms Application application which should show image on the PictureBox control.

To retrieve this image from DICOMDIR file I use fo-dicom library (driven by this guide):

....
private void MainForm_Load(object sender, EventArgs e)
{
    ImageManager.SetImplementation(WinFormsImageManager.Instance);
}
....

// this function is just for example
// real function is bit complicated
private void ShowImage()
{
    // Getting DICOM file, retrieving all info from it
    // Getting dicomDataset instance
    ....

    var id = dicomDataset.Get<string>(DicomTag.ReferencedFileID, -1);
    var dicomImage = new DicomImage(id);
    var bitmap = dicomImage.RenderImage().AsBitmap();
    pictureBox.Image = bitmap ?? pictureBox.ErrorImage;
}

When image is retrieving all works fine. But as soon as I maximize my MainForm, I got System.ArgumentException with Parameter is not valid message:

It looks like this is a .NET Framework bug, but maybe there is a way to fix it by overrideing OnPaint() method of PictureBox control?

Have anyone see this bug previously?

Thanks in advance.

P.S. During development this project I use following software:

  1. Windows 10 x64
  2. Visual Studio 2017 Community Edition
  3. .NET Framework 4.5.1
  4. fo-dicom version 3.0.2

EDIT #1

The same issue with Panel instead of PictureBox:


回答1:


You are facing a known and already fixed bug in fo-dicom 3.0.2. See also https://github.com/fo-dicom/fo-dicom/issues/634. For performance reason the Bitmap, that DicomImage.RenderImage().AsBitmap() returns, does not have its own pixel data, but has a pointer to the bytes of DicomImage. So the AsBitmap() does not duplicate all the pixel data in memory. But if you instanciate the DicomImage in a local variable and save the Bitmap in the control, then the DicomImage is disposed at the end of the method and the pixel data gets garbace collected. The next time, the Bitmap tries to access the pixel data this exception happens.

The next release will have two methods: AsSharedBitmap() - the same as now but more obvious to the user - and AsClonedBitmap().

The workaround now is, to copy the pixel data manually by calling:

var bitmap = dicomImage.RenderImage().AsBitmap().Clone();



来源:https://stackoverflow.com/questions/50313402/c-sharp-system-drawing-image-get-width-throws-exception-on-winforms-form-is-ma

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!