Skip to content

Commit

Permalink
Add more helpful error message when saving JPEG with alpha band
Browse files Browse the repository at this point in the history
  • Loading branch information
djhoese committed May 4, 2020
1 parent 19eb077 commit b24c117
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 1 deletion.
4 changes: 4 additions & 0 deletions trollimage/tests/test_image.py
Original file line number Diff line number Diff line change
Expand Up @@ -808,6 +808,10 @@ def test_save(self):
img = xrimage.XRImage(data)
with NamedTemporaryFile(suffix='.jpg') as tmp:
img.save(tmp.name, fill_value=0)
# Jpeg fails without fill value (no alpha handling)
with NamedTemporaryFile(suffix='.jpg') as tmp:
# make sure fill_value is mentioned in the error message
self.assertRaisesRegex(OSError, "fill_value", img.save, tmp.name)
# As PNG that support alpha channel
img = xrimage.XRImage(data)
with NamedTemporaryFile(suffix='.png') as tmp:
Expand Down
21 changes: 20 additions & 1 deletion trollimage/xrimage.py
Original file line number Diff line number Diff line change
Expand Up @@ -263,6 +263,25 @@ def invert_scale_offset(scale, offset):
return 1 / scale, -offset / scale


@delayed(nout=1, pure=True)
def delayed_pil_save(img, *args, **kwargs):
"""Dask delayed saving of PIL Image object.
Special wrapper to handle `fill_value` try/except catch and provide a
more useful error message.
"""
try:
img.save(*args, **kwargs)
except OSError as e:
# ex: cannot write mode LA as JPEG
if "A as JPEG" in str(e):
new_msg = ("Image mode not supported for this format. Specify "
"`fill_value=0` to set invalid values to black.")
raise OSError(new_msg) from e
raise


class XRImage(object):
"""Image class using an :class:`xarray.DataArray` as internal storage.
Expand Down Expand Up @@ -551,7 +570,7 @@ def pil_save(self, filename, fformat=None, fill_value=None,
format_kwargs['pnginfo'] = self._pngmeta()

img = self.pil_image(fill_value, compute=False)
delay = img.save(filename, fformat, **format_kwargs)
delay = delayed_pil_save(img, filename, fformat, **format_kwargs)
if compute:
return delay.compute()
return delay
Expand Down

0 comments on commit b24c117

Please sign in to comment.