add support for serializing to file-like objects (e.g. StringIO) to PIL plugin

This commit is contained in:
wilsaj
2012-07-20 15:22:53 -05:00
parent d2e0484845
commit 605a4e2cd7
+11 -3
View File
@@ -59,17 +59,21 @@ def _palette_is_grayscale(pil_image):
return np.allclose(np.diff(valid_palette), 0)
def imsave(fname, arr):
def imsave(fname, arr, format_str=None):
"""Save an image to disk.
Parameters
----------
fname : str
fname : str or file-like object
Name of destination file.
arr : ndarray of uint8 or float
Array (image) to save. Arrays of data-type uint8 should have
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.
Notes
-----
@@ -101,7 +105,11 @@ def imsave(fname, arr):
arr = arr.astype(np.uint8)
img = Image.fromstring(mode, (arr.shape[1], arr.shape[0]), arr.tostring())
img.save(fname)
if isinstance(fname, basestring):
img.save(fname, format=format_str)
elif callable(getattr(fname, 'write', None)):
img.save(fname, format=format_str)
def imshow(arr):