Skip to content

Commit

Permalink
Support file like objects for images
Browse files Browse the repository at this point in the history
  • Loading branch information
RedBeardCode committed Oct 12, 2019
1 parent 666fad6 commit 5cadff6
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 11 deletions.
29 changes: 19 additions & 10 deletions panel/pane/image.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,10 +39,16 @@ class ImageBase(DivPaneBase):
@classmethod
def applies(cls, obj):
imgtype = cls.imgtype
return (hasattr(obj, '_repr_'+imgtype+'_') or
(isinstance(obj, string_types) and
((os.path.isfile(obj) and obj.endswith('.'+imgtype)) or
cls._is_url(obj))))
if hasattr(obj, '_repr_{}_'.format(imgtype)):
return True
if isinstance(obj, string_types):
if os.path.isfile(obj) and obj.endswith('.'+imgtype):
return True
if cls._is_url(obj):
return True
if hasattr(obj, 'read'): # Check for file like object
return True
return False

@classmethod
def _is_url(cls, obj):
Expand All @@ -51,12 +57,15 @@ def _is_url(cls, obj):
and obj.endswith('.'+cls.imgtype))

def _img(self):
if not isinstance(self.object, string_types):
return getattr(self.object, '_repr_'+self.imgtype+'_')()
elif os.path.isfile(self.object):
with open(self.object, 'rb') as f:
return f.read()
else:
if hasattr(self.object, '_repr_{}_'.format(self.imgtype)):
return getattr(self.object, '_repr_' + self.imgtype + '_')()
if isinstance(self.object, string_types):
if os.path.isfile(self.object):
with open(self.object, 'rb') as f:
return f.read()
if hasattr(self.object, 'read'):
return self.object.read()
if self._is_url(self.object):
import requests
r = requests.request(url=self.object, method='GET')
return r.content
Expand Down
12 changes: 11 additions & 1 deletion panel/tests/pane/test_image.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from base64 import b64decode, b64encode

from panel.pane import GIF, JPG, PNG, SVG

from io import BytesIO

def test_svg_pane(document, comm):
rect = """
Expand Down Expand Up @@ -53,3 +53,13 @@ def test_imgshape():
w,h = t._imgshape(b64decode(twopixel[t.name.lower()]))
assert w == 2
assert h == 1

def test_load_from_io():
"""Testing a loading a image from a ByteIo"""
memory = BytesIO()
with open('../test_data/logo.png', 'rb') as image_file:
memory.write(image_file.read())
memory.seek(0)
image_pane = GIF(memory)
image_data = image_pane._img()
assert b'PNG' in image_data
Binary file added panel/tests/test_data/logo.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.

0 comments on commit 5cadff6

Please sign in to comment.