Skip to content

Commit

Permalink
Merge pull request scikit-image#613 from adamw523/master
Browse files Browse the repository at this point in the history
support for saving to file-like object in imsave
  • Loading branch information
tonysyu committed Jun 28, 2013
2 parents 2e80b81 + a95824c commit c61e043
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 3 deletions.
9 changes: 6 additions & 3 deletions skimage/io/_plugins/pil_plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,9 +71,8 @@ def imsave(fname, arr, format_str=None):
values in [0, 255], whereas floating-point arrays must be
in [0, 1].
format_str: str
Format to save as, this is required if using a file-like object;
this is optional if fname is a string and the format can be
derived from the extension.
Format to save as, this is defaulted to PNG if using a file-like
object; this will be derived from the extension if fname is a string
Notes
-----
Expand Down Expand Up @@ -104,6 +103,10 @@ def imsave(fname, arr, format_str=None):
# Force all integers to bytes
arr = arr.astype(np.uint8)

# default to PNG if file-like object
if not isinstance(fname, basestring) and format_str is None:
format_str = "PNG"

img = Image.fromstring(mode, (arr.shape[1], arr.shape[0]), arr.tostring())
img.save(fname, format=format_str)

Expand Down
16 changes: 16 additions & 0 deletions skimage/io/tests/test_io.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

from numpy.testing import *
import numpy as np
from StringIO import StringIO

import skimage.io as io
from skimage import data_dir
Expand All @@ -28,5 +29,20 @@ def test_imread_url():
assert image.shape == (512, 512)


def test_imsave_filelike():
shape = (2, 2)
image = np.zeros(shape)
s = StringIO()

# save to file-like object
io.imsave(s, image)

# read from file-like object
s.seek(0)
out = io.imread(s)
assert out.shape == shape
np.testing.assert_allclose(out, image)


if __name__ == "__main__":
run_module_suite()

0 comments on commit c61e043

Please sign in to comment.