Skip to content

Fix #5302: Proper alpha-blending for jpeg #5324

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Oct 28, 2015
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
Fix #5302: Proper alpha-blending for jpeg
  • Loading branch information
mdboom committed Oct 26, 2015
commit bdea63d1c852da5393e6844fc7edd1659e0dab70
7 changes: 5 additions & 2 deletions lib/matplotlib/backends/backend_agg.py
Original file line number Diff line number Diff line change
Expand Up @@ -551,7 +551,6 @@ def print_to_buffer(self):
return result

if _has_pil:

# add JPEG support
def print_jpg(self, filename_or_obj, *args, **kwargs):
"""
Expand All @@ -573,14 +572,18 @@ def print_jpg(self, filename_or_obj, *args, **kwargs):
buf, size = self.print_to_buffer()
if kwargs.pop("dryrun", False):
return
# The image is "pasted" onto a white background image to safely
# handle any transparency
image = Image.frombuffer('RGBA', size, buf, 'raw', 'RGBA', 0, 1)
background = Image.new('RGB', size, (255, 255, 255))
background.paste(image, image)
options = restrict_dict(kwargs, ['quality', 'optimize',
'progressive'])

if 'quality' not in options:
options['quality'] = rcParams['savefig.jpeg_quality']

return image.save(filename_or_obj, format='jpeg', **options)
return background.save(filename_or_obj, format='jpeg', **options)
print_jpeg = print_jpg

# add TIFF support
Expand Down
22 changes: 22 additions & 0 deletions lib/matplotlib/tests/test_image.py
Original file line number Diff line number Diff line change
Expand Up @@ -453,6 +453,28 @@ def test_nonuniformimage_setnorm():
im = NonUniformImage(ax)
im.set_norm(plt.Normalize())

@knownfailureif(not HAS_PIL)
@cleanup
def test_jpeg_alpha():
plt.figure(figsize=(1, 1), dpi=300)
# Create an image that is all black, with a gradient from 0-1 in
# the alpha channel from left to right.
im = np.zeros((300, 300, 4), dtype=np.float)
im[..., 3] = np.linspace(0.0, 1.0, 300)

plt.figimage(im)

buff = io.BytesIO()
plt.savefig(buff, transparent=True, format='jpg', dpi=300)

buff.seek(0)
image = Image.open(buff)

# If this fails, there will be only one color (all black). If this
# is working, we should have all 256 shades of grey represented.
assert len(image.getcolors(256)) == 256


if __name__=='__main__':
import nose
nose.runmodule(argv=['-s','--with-doctest'], exit=False)