Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit bc29c71

Browse files
committed
tweak double-encode logic for image data
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 #3081
1 parent 699a45a commit bc29c71

1 file changed

Lines changed: 15 additions & 4 deletions

File tree

IPython/utils/jsonutil.py

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -97,7 +97,9 @@ def date_default(obj):
9797

9898
# constants for identifying png/jpeg data
9999
PNG = b'\x89PNG\r\n\x1a\n'
100+
PNG64 = encodebytes(PNG)
100101
JPEG = b'\xff\xd8'
102+
JPEG64 = encodebytes(JPEG)
101103

102104
def encode_images(format_dict):
103105
"""b64-encodes images in a displaypub format dict
@@ -120,12 +122,21 @@ def encode_images(format_dict):
120122
121123
"""
122124
encoded = format_dict.copy()
125+
123126
pngdata = format_dict.get('image/png')
124-
if isinstance(pngdata, bytes) and pngdata[:8] == PNG:
125-
encoded['image/png'] = encodebytes(pngdata).decode('ascii')
127+
if isinstance(pngdata, bytes):
128+
# make sure we don't double-encode
129+
if pngdata[:13] != PNG64:
130+
pngdata = encodebytes(pngdata)
131+
encoded['image/png'] = pngdata.decode('ascii')
132+
126133
jpegdata = format_dict.get('image/jpeg')
127-
if isinstance(jpegdata, bytes) and jpegdata[:2] == JPEG:
128-
encoded['image/jpeg'] = encodebytes(jpegdata).decode('ascii')
134+
if isinstance(jpegdata, bytes):
135+
# make sure we don't double-encode
136+
if jpegdata[:5] != JPEG64:
137+
jpegdata = encodebytes(jpegdata)
138+
encoded['image/jpeg'] = jpegdata.decode('ascii')
139+
129140
return encoded
130141

131142

0 commit comments

Comments
 (0)