imread icon indicating copy to clipboard operation
imread copied to clipboard

Write to buffer or return bytes

Open flekschas opened this issue 8 years ago • 4 comments

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.

flekschas avatar Mar 12 '18 19:03 flekschas

This would be a good feature, but it would require more effort than I am currently willing to invest.

luispedro avatar Mar 12 '18 19:03 luispedro

I understand. I'll see if I can get something to work when I have some free time.

flekschas avatar Mar 12 '18 20:03 flekschas

Here are some pointers:

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

  2. Then, in the imsave_may_multi function, (https://github.com/luispedro/imread/blob/b2d55695b962e1b75cc36afc1552646c37122534/imread/_imread.cpp#L286), you use it instead of the current fd_source_sink (depending on the input, naturally).

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

luispedro avatar Mar 12 '18 20:03 luispedro

@flekschas as per the pointers offered by @luispedro – I have some things that may help you:

… 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

fish2000 avatar Apr 11 '18 15:04 fish2000