Skip to content

Memory leak - drawing text #7540

@Thomas-2503

Description

@Thomas-2503

Hi :)

I have found a memory leak when drawing text with Pillow.

How to reproduce

  1. Pull a python docker image - I used python:3.8-slim
  2. Install Pillow - I used version 10.1.0
  3. Open an image via Pillow in a python script and just draw text (see code beneath)
  4. Optional: Install psutils to output RAM usage
  5. Run the docker image with the python script and use an image of your choice (test_pillow_image.png):

Docker run command (example)
docker run -it --rm --name pillow_python_test -v "$PWD":/usr/src/myapp -w /usr/src/myapp python_for_pillow python test_pillow.py

python_for_pillow is my docker python:3.8-slim image with Pillow (10.1.0) and psutils installed.

Python script to reproduce the memory leak (test_pillow.py)

import os
import time

from PIL import Image, ImageDraw

import psutil

if __name__ == '__main__':
    start_time = time.time()

    pid = os.getpid()
    process = psutil.Process(pid)

    while True:
        image = Image.open('test_pillow_image.png')
        image_draw = ImageDraw.Draw(image, 'RGBA')

        for i in range(0, 1000):
            image_draw.text((200, 200), 'Hi hi hi :)')

            if time.time() - start_time >= 10:  # output RAM usage every 10 seconds
                start_time = time.time()
                memory_info = process.memory_info()
                print(f'RAM usage: {memory_info.rss / 1000 / 1000} MB')

        image.close()

This code outputs the RAM usage every 10 seconds. Example output:

image
The RAM usage is increasing by approximately 2 MB every 10 seconds. This does not happen when drawing rectangles. If you replace the for loop with while true, the memory leak can be observed as well.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions