MCPcopy Index your code
hub / github.com/python-openxml/python-docx / Image

Class Image

src/docx/image/image.py:18–165  ·  view source on GitHub ↗

Graphical image stream such as JPEG, PNG, or GIF with properties and methods required by ImagePart.

Source from the content-addressed store, hash-verified

16
17
18class Image:
19 """Graphical image stream such as JPEG, PNG, or GIF with properties and methods
20 required by ImagePart."""
21
22 def __init__(self, blob: bytes, filename: str, image_header: BaseImageHeader):
23 super(Image, self).__init__()
24 self._blob = blob
25 self._filename = filename
26 self._image_header = image_header
27
28 @classmethod
29 def from_blob(cls, blob: bytes) -> Image:
30 """Return a new |Image| subclass instance parsed from the image binary contained
31 in `blob`."""
32 stream = io.BytesIO(blob)
33 return cls._from_stream(stream, blob)
34
35 @classmethod
36 def from_file(cls, image_descriptor: str | IO[bytes]):
37 """Return a new |Image| subclass instance loaded from the image file identified
38 by `image_descriptor`, a path or file-like object."""
39 if isinstance(image_descriptor, str):
40 path = image_descriptor
41 with open(path, "rb") as f:
42 blob = f.read()
43 stream = io.BytesIO(blob)
44 filename = os.path.basename(path)
45 else:
46 stream = image_descriptor
47 stream.seek(0)
48 blob = stream.read()
49 filename = None
50 return cls._from_stream(stream, blob, filename)
51
52 @property
53 def blob(self):
54 """The bytes of the image 'file'."""
55 return self._blob
56
57 @property
58 def content_type(self) -> str:
59 """MIME content type for this image, e.g. ``'image/jpeg'`` for a JPEG image."""
60 return self._image_header.content_type
61
62 @lazyproperty
63 def ext(self):
64 """The file extension for the image.
65
66 If an actual one is available from a load filename it is used. Otherwise a
67 canonical extension is assigned based on the content type. Does not contain the
68 leading period, e.g. 'jpg', not '.jpg'.
69 """
70 return os.path.splitext(self._filename)[1][1:]
71
72 @property
73 def filename(self):
74 """Original image file name, if loaded from disk, or a generic filename if
75 loaded from an anonymous stream."""

Calls

no outgoing calls

Used in the wild real call sites across dependent graphs

searching dependent graphs…