-
-
Notifications
You must be signed in to change notification settings - Fork 2.4k
Closed
Labels
Description
Hi :)
I have found a memory leak when drawing text with Pillow.
How to reproduce
- Pull a python docker image - I used python:3.8-slim
- Install Pillow - I used version 10.1.0
- Open an image via Pillow in a python script and just draw text (see code beneath)
- Optional: Install psutils to output RAM usage
- 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:

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.
muxamilian