Coverage for /home/martinb/.local/share/virtualenvs/camcops/lib/python3.6/site-packages/openpyxl/drawing/image.py : 35%

Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1# Copyright (c) 2010-2020 openpyxl
3from io import BytesIO
5try:
6 from PIL import Image as PILImage
7except ImportError:
8 PILImage = False
11def _import_image(img):
12 if not PILImage:
13 raise ImportError('You must install Pillow to fetch image objects')
15 if not isinstance(img, PILImage.Image):
16 img = PILImage.open(img)
18 return img
21class Image(object):
22 """Image in a spreadsheet"""
24 _id = 1
25 _path = "/xl/media/image{0}.{1}"
26 anchor = "A1"
28 def __init__(self, img):
30 self.ref = img
31 mark_to_close = isinstance(img, str)
32 image = _import_image(img)
33 self.width, self.height = image.size
35 try:
36 self.format = image.format.lower()
37 except AttributeError:
38 self.format = "png"
39 if mark_to_close:
40 # PIL instances created for metadata should be closed.
41 image.close()
44 def _data(self):
45 """
46 Return image data, convert to supported types if necessary
47 """
48 img = _import_image(self.ref)
49 # don't convert these file formats
50 if self.format in ['gif', 'jpeg', 'png']:
51 img.fp.seek(0)
52 fp = img.fp
53 else:
54 fp = BytesIO()
55 img.save(fp, format="png")
56 fp.seek(0)
58 return fp.read()
61 @property
62 def path(self):
63 return self._path.format(self._id, self.format)