Provides access to the image parts in a package.
| 123 | |
| 124 | |
| 125 | class _ImageParts(object): |
| 126 | """Provides access to the image parts in a package.""" |
| 127 | |
| 128 | def __init__(self, package): |
| 129 | super(_ImageParts, self).__init__() |
| 130 | self._package = package |
| 131 | |
| 132 | def __iter__(self) -> Iterator[ImagePart]: |
| 133 | """Generate a reference to each |ImagePart| object in the package.""" |
| 134 | image_parts = [] |
| 135 | for rel in self._package.iter_rels(): |
| 136 | if rel.is_external: |
| 137 | continue |
| 138 | if rel.reltype != RT.IMAGE: |
| 139 | continue |
| 140 | image_part = rel.target_part |
| 141 | if image_part in image_parts: |
| 142 | continue |
| 143 | image_parts.append(image_part) |
| 144 | yield image_part |
| 145 | |
| 146 | def get_or_add_image_part(self, image_file: str | IO[bytes]) -> ImagePart: |
| 147 | """Return |ImagePart| object containing the image in `image_file`. |
| 148 | |
| 149 | `image_file` can be either a path to an image file or a file-like object |
| 150 | containing an image. If an image part containing this same image already exists, |
| 151 | that instance is returned, otherwise a new image part is created. |
| 152 | """ |
| 153 | image = Image.from_file(image_file) |
| 154 | image_part = self._find_by_sha1(image.sha1) |
| 155 | return image_part if image_part else ImagePart.new(self._package, image) |
| 156 | |
| 157 | def _find_by_sha1(self, sha1: str) -> ImagePart | None: |
| 158 | """ |
| 159 | Return an |ImagePart| object belonging to this package or |None| if |
| 160 | no matching image part is found. The image part is identified by the |
| 161 | SHA1 hash digest of the image binary it contains. |
| 162 | """ |
| 163 | for image_part in self: |
| 164 | # ---skip unknown/unsupported image types, like SVG--- |
| 165 | if not hasattr(image_part, "sha1"): |
| 166 | continue |
| 167 | if image_part.sha1 == sha1: |
| 168 | return image_part |
| 169 | return None |
| 170 | |
| 171 | |
| 172 | class _MediaParts(object): |
no outgoing calls
searching dependent graphs…