Write to buffer or return bytes
This is more a question or feature request / idea rather than an issue.
If I am not mistaken it's currently not possible to write to a buffer or return the written bytes somehow right? What do you think about expanding the interface to support something like:
buf = BytesIO()
imsave(buf, my_fancy_array, formatstr='png')
If this is out of scope never mind. I am just curious.
This would be a good feature, but it would require more effort than I am currently willing to invest.
I understand. I'll see if I can get something to work when I have some free time.
Here are some pointers:
-
You should probably do a derived class from
byte_sink(see https://github.com/luispedro/imread/blob/b2d55695b962e1b75cc36afc1552646c37122534/imread/lib/base.h#L63) which writes to a buffer in memory. -
Then, in the
imsave_may_multifunction, (https://github.com/luispedro/imread/blob/b2d55695b962e1b75cc36afc1552646c37122534/imread/_imread.cpp#L286), you use it instead of the currentfd_source_sink(depending on the input, naturally). -
Finally, convert it to a memory object and return it to Python.
A few things to watch out for:
- some writers need to seek in the output they've written
- writing happens without the GIL so avoid calling Python API functions.
HTH Luis
@flekschas as per the pointers offered by @luispedro – I have some things that may help you:
- A subclass of the
byte_sourcetype that operates on thePy_bufferstructure from PEP 3118 and supports seeking: header and source - Context-manager-esque RAII structures for GIL state-management and GIL-aware
PyFileObject*-based I/O
… if you’re curious, I also have an example of a method returning a PyObject* containing the bytes that result from calling ImageFormat::write(…), and a Python C-API module method in which it gets used.
I, too, HTH. Salud,
-Alex