Home > OS >  Bitmap access violation exception with camera image
Bitmap access violation exception with camera image

Time:09-16

In my WPF application images are taken with a camera use a view and then passed as bitmaps to another when it's closed via eventargs. However, when I then try to process the images I get the AccessViolationException. This does not occure when I process the images before they are passed or when I use images loaded from a file.

Getting the image from the camera (The PtCamera class is my wrapper for the Camera class from the API)

 Bitmap GetRefImage(PtCamera cam)
    {

        Bitmap image = new Bitmap(2560, 1920, System.Drawing.Imaging.PixelFormat.Format24bppRgb);

        if (cam.IsConnected)
        {
           cam.FetchImage(out image);
        }
        else
        {
           ErrorOccurred?.Invoke(this, $"GetRefImage: {cam.Error}");
        }
        
        return image;
    }

In this context I can access the bitmap and process it as I like.

After passing the bitmap when the view is closed:

void CloseZoomedView(bool isConf)
    {
        if (cam is object && cam.IsConnected)
            cam.Close();
        ZoomClosingArgs eArg = new ZoomClosingArgs()
        {
            IsConfirmed = isConf,
            RefImage = refImage,
        };
        ClosingZoom?.Invoke(this, eArg);
    }

The exception occurs directly when accessing the data in the other viewmodel:

void HandleZoomImageClosed(object sender, ZoomClosingArgs e)
{
    if (e is object && e.IsConfirmed)
    {
        Color test = e.RefImage.GetPixel(0, 0);
        //...
    }
 }

The bitmap is generated by accessing the memory of the camera via FetchImage()

   public void FetchImage(out Bitmap image)
   {
      camera.Memory.GetActive(out int memID);
      camera.Memory.ToBitmap(memID, out image);
   }

If i replace the code in FetchImage() with just a new Bitmap from file

image = new Bitmap(@"d:\testimage.png")

It works without problems in any context.

The API documentation simply states the following:

Accessible

Camera.Memory.ToBitmap

Syntax

uEye.Memory.ToBitmap(int s32MemId, out System.Drawing.Bitmap bitmap)

Description

Returns a bitmap which contains the image. The method uses the already allocated image memory and the image is displayed in the format you specified when allocating the image memory.

Any hints are much appreciated.

CodePudding user response:

I was closing my camera object too early. In CloseZoomedView() the cam.Close() method releases all the memory areas taken up by the camera. With passing a new Bitmap before closing it works like a charm.

void CloseZoomedView(bool isConf)
{        
     ZoomClosingArgs eArg = new ZoomClosingArgs()
     {
        IsConfirmed = isConf,
        RefImage = new Bitmap(refImage),
     };
     
     if (cam is object && cam.IsConnected)
        cam.Close();

     ClosingZoom?.Invoke(this, eArg);
 }
  • Related