# Cell magic to save image output as a .png file

**URL:** <https://discourse.jupyter.org/t/cell-magic-to-save-image-output-as-a-png-file/11906>\
**Category:** ipynb\
**Tags:** jupyterlab, help-wanted\
**Created:** [November 27, 2021, 6:48pm UTC](https://discourse.jupyter.org/t/cell-magic-to-save-image-output-as-a-png-file/11906 "2021-11-27T18:48:51Z")\
**Posts on this page:** 1\
**Showing post:** 4

<div class="post-metadata">

**Author:** ![krassowski](https://yyz1.discourse-cdn.com/flex031/user_avatar/discourse.jupyter.org/krassowski/32/1685_2.png) [@krassowski](https://discourse.jupyter.org/u/krassowski)\
**Post date:** [November 28, 2021, 2:59pm UTC](https://discourse.jupyter.org/t/cell-magic-to-save-image-output-as-a-png-file/11906/4 "2021-11-28T14:59:54Z")

</div>

> Would it be possible to make a package out of your implementation?

Yes. Personally, I would not install it as-is though, too little benefit (equivalent to 15-line of code) but maybe after expanding to cover more cases it could be useful.

> Or would it be possible to add this feature to an already existing library (e.g. IPython or Ipywidgets)?

I could see a case for including something more generic (`%capture_images`) in [IPython-contrib](https://github.com/ipython-contrib), but I am not a maintainer there so the decision on accepting it would be up to somebody else 😉

> Saving the output with `%%capture_png` does not display the image in Jupyter. That is also the case when using the `%%capture` magic.

Well, it’s called _capture_, this is what `capture` functions do. If it should display output it ought to be called `tee_png` (after [`tee`](https://en.wikipedia.org/wiki/Tee_(command))) or `save_png`. But, as you correctly noticed the modifications needed to display the outputs are minimal (though the order can be lost if you also have non-image outputs - I don’t have a solution for that of top of my head).

> [@kolibril13](#):
>
> - the current implementation has a dependency to PIL, maybe it is also possible to save the BytesIO object to a png file without PIL?

Possibly - [it’s barely 200 lines of code](https://github.com/python-pillow/Pillow/blob/95cff6e959bb3c37848158ed2145d49d49806a31/src/PIL/PngImagePlugin.py#L1191-L1362) (+ maybe few hundreds more in helper methods); personally I would accept the dependency (on PIL or pillow) 🙂

---

_[View the full topic](https://discourse.jupyter.org/t/cell-magic-to-save-image-output-as-a-png-file/11906)._
