Skip to content

Query regarding shared buffer #6768

@time4tea

Description

@time4tea

Just wondering about using shared buffers. According to the docs - Image.frombuffer() is a way to share an image buffer. All the code seems to do the "right thing" - with PyImaging_MapBuffer setting up all the pointers etc. https://github.com/python-pillow/Pillow/blob/main/src/map.c#L52

However, in Image.frombuffer() it sets im.readonly to 1, ( https://github.com/python-pillow/Pillow/blob/main/src/PIL/Image.py#L2937 ) which means that any subsequent draw operations will clone the image - making it non-shared again.( https://github.com/python-pillow/Pillow/blob/main/src/PIL/ImageDraw.py#L63 )

It does seem possible to set im.readonly to 0 again after running Image.frombuffer() - and drawing works fine - but it looks like this was done on purpose - https://github.com/python-pillow/Pillow/blob/main/CHANGES.rst - for version 1.1.2c1 -

The "load" method now sets the "readonly" attribute for memory-mapped images. Operations that modifies an image in place (such as "paste" and drawing operations) creates an in-memory copy of the image, if necessary. (before this change, any attempt to modify a memory-mapped image resulted in a core dump...)

This comment is very old! - I was wondering if it was considered safe to set im.readonly to 0 and share image data via a buffer.

something along the lines of (very approximately!)

[...]
        self._buffer_size = (dimensions.x * dimensions.y * 4)
        self._buffer = ctypes.create_string_buffer(self._buffer_size)
        self._image = Image.frombuffer("RGBA", (dimensions.x, dimensions.y), self._buffer, "raw", "RGBA", 0, 1)
        self._image.readonly = 0

Is this a very bad idea?

Thanks!

James

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