Facing "Access violation error" while blurring the face in image

Rajat Kumar Jha 20 Reputation points
2023-03-17T17:22:06.45+00:00

In my C# .NET Azure Function code I am trying to blur faces in Image.

For detecting face coordinates I use Face API provide by Microsoft Azure Cognitive Services.

After I get the coordinates, below is the code that blur the Image:-

private static async Task TrackBlurFaces(FaceRectangle[] faceRects, string sourceImage, string destinationImage,ILogger log)
{
try
{
   if (faceRects.Length > 0)
     {
       using FileStream stream = System.IO.File.OpenRead(sourceImage), output = System.IO.File.OpenWrite(destinationImage);
       byte[] imageContent = new byte[stream.Length];
       stream.Position = 0;
       stream.Read(imageContent, 0, (int)stream.Length);
       using MemoryStream mstrm = new MemoryStream(imageContent);
       var image = new Image<Color, uint>(mstrm);
       foreach (var faceRect in faceRects)
       {
          var rectangle = new Rectangle(
          faceRect.Left,
          faceRect.Top,
          faceRect.Width,
          faceRect.Height);
          image = image.BoxBlur(10, rectangle);
       }
       image.Save(output);
       output.Close();
       stream.Close();
       output.Dispose(); 
       stream.Dispose();
       log.LogInformation("Bluring image done on " + sourceImage);
    }
}
catch(Exception ex)
{
 log.LogError("Exception occurs in method TrackBlurFaces : " + ex.Message);
 throw ex;
}
}

In above code I am using Ngonzalez.ImageProcessorCore nuget package for blurring the image. This code works most of the time but sometimes I get "Access violation error" at below line

image = image.BoxBlur(10, rectangle);

Now the problem I am facing due to this is :-

  1. Whenever I encounter this error, my Azure function stops completely, it doesn't go to catch block
  2. And the face doesn't get blurred

Now I have searched on this exception and most of the sites told me that it happens because "An access violation occurs in unmanaged or unsafe code when the code attempts to read or write to memory that has not been allocated." But my question is why doesn't it happen for every image if my some part of code is "unsafe" and only occurs intermittently.

So can anyone help me know what may be the actual problem or if any other nuget packages will help me and also let me know if any more information about my code required.

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,301 questions
{count} votes