Skip to content

Commit

Permalink
tweak double-encode logic for image data
Browse files Browse the repository at this point in the history
instead of only b64-encoding for valid image data,
b64-encode unless it is specifically detected as b64-encoded valid image data.
This prevents garbage data from skipping the b64 step,
and causing unicode errors.

Closes ipython#3081
  • Loading branch information
minrk committed Mar 26, 2013
1 parent c271841 commit 7e8699f
Showing 1 changed file with 15 additions and 4 deletions.
19 changes: 15 additions & 4 deletions IPython/utils/jsonutil.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,9 @@ def date_default(obj):

# constants for identifying png/jpeg data
PNG = b'\x89PNG\r\n\x1a\n'
PNG64 = encodebytes(PNG)
JPEG = b'\xff\xd8'
JPEG64 = encodebytes(JPEG)

def encode_images(format_dict):
"""b64-encodes images in a displaypub format dict
Expand All @@ -120,12 +122,21 @@ def encode_images(format_dict):
"""
encoded = format_dict.copy()

pngdata = format_dict.get('image/png')
if isinstance(pngdata, bytes) and pngdata[:8] == PNG:
encoded['image/png'] = encodebytes(pngdata).decode('ascii')
if isinstance(pngdata, bytes):
# make sure we don't double-encode
if pngdata[:13] != PNG64:
pngdata = encodebytes(pngdata)
encoded['image/png'] = pngdata.decode('ascii')

jpegdata = format_dict.get('image/jpeg')
if isinstance(jpegdata, bytes) and jpegdata[:2] == JPEG:
encoded['image/jpeg'] = encodebytes(jpegdata).decode('ascii')
if isinstance(jpegdata, bytes):
# make sure we don't double-encode
if jpegdata[:5] != JPEG64:
jpegdata = encodebytes(jpegdata)
encoded['image/jpeg'] = jpegdata.decode('ascii')

return encoded


Expand Down

0 comments on commit 7e8699f

Please sign in to comment.