Skip to content

Memory leak when using MagickImage constructor with Stream argument for large WebP image. #1163

@REC-James

Description

@REC-James

Magick.NET version

10.1.0

Environment (Operating system, version and so on)

Windows 11

Description

Hi. I think I've found a memory leak specifically in the MagickImage constructor that takes a Stream argument.

When loading a 6MB animated WebP image using the MagickImage class, I've noticed that the large memory usage used during the loading does not clear itself after the Using block. This only happens when using the constructor that takes a Stream argument, the other constructors seem to work fine. (I understand that Magick.NET loads in the image as uncompressed pixel data, so the initial memory usage is high, but it clears after the object is disposed normally.) Shown below I have two sets of code to demonstrate the problem.

I can provide a large animated WebP file if you need, but I will have to edit it to take out our customer's specific information first.

Steps to Reproduce

This code shows that the memory after loading the image is released correctly when using the file path constructor. If you look at the memory usage in the Task Manager once it is at the ReadLine() line, it will be low.

using System;
using ImageMagick;

namespace WebPMemLeak
{
    class Program
    {
        static void Main(string[] args)
        {
            const string IMAGE_PATH = "test.webp";

            using (MagickImage image = new MagickImage(IMAGE_PATH))
            {
                Console.WriteLine("Image loaded");
            }
            Console.WriteLine("Note the memory usage in the Task Manager, it is low.");
            Console.ReadLine();
        }
    }
}

This code shows that the memory after loading the image is still high when using the Stream constructor. If you look at the memory usage in the Task Manager once it is at the ReadLine() line, it will be high. Note that the file stream is closed properly with a Using block.

using System;
using ImageMagick;

namespace WebPMemLeak
{
    class Program
    {
        static void Main(string[] args)
        {
            const string IMAGE_PATH = "test.webp";

            using (System.IO.FileStream fs = new System.IO.FileStream(IMAGE_PATH, System.IO.FileMode.Open, System.IO.FileAccess.Read))
            {
                using (MagickImage image = new MagickImage(fs))
                {
                    Console.WriteLine("Image loaded");
                }
            }
            Console.WriteLine("Note the memory usage in the Task Manager, it is high.");
            Console.ReadLine();
        }
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions