Skip to content

Change Image.tobytes return type to ByteArray or add a Image.tobytearray method #5815

@FirefoxMetzger

Description

@FirefoxMetzger

Currently the method Image.tobytes returns a byte string. There is nothing inherently bad about this, except that the returned bytes are read only (ofc) since bytes are immutable.

The consequence of this is that Image.__array__ does an extra copy when calling

return np.array(ArrayData(), dtype)

that (I think) can be avoided. The data is copied from the immutable bytes string into a new mutable memory block around which the array is constructed.

This copy can be avoided in a few ways:

  1. Chance the code in Image.__array__ to (roughly) np.frombuffer(self.tobytes(), dtype=dtype).reshape(shape). The downside is that the result is read-only (result.flags['WRITEABLE'] == False) which may be undesirable.
  2. Change the code in Image.tobytes to return a bytearray. This may require work, depending on what encoder returns (didn't dive that far into the code), and it may be undesirable because type(Image.tobytes()) changes.
  3. Introduce a new Image.tobytearray method that essentially mirrors Image.tobytes, except that it creates a mutable buffer. This resolves the problems that come with changing Image.tobytes return type, but may still need more work.

Would this be something interesting and/or useful to do?

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