| Conditions | 4 |
| Total Lines | 52 |
| Code Lines | 19 |
| Lines | 0 |
| Ratio | 0 % |
| Changes | 0 | ||
Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.
For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.
Commonly applied refactorings include:
If many parameters/temporary variables are present:
| 1 | # Copyright Pincer 2021-Present |
||
| 130 | @classmethod |
||
| 131 | def from_pillow_image( |
||
| 132 | cls, |
||
| 133 | img: IMAGE_TYPE, |
||
| 134 | filename: Optional[str] = None, |
||
| 135 | image_format: Optional[str] = None, |
||
| 136 | **kwargs, |
||
| 137 | ) -> File: |
||
| 138 | """Creates a file object from a PIL image |
||
| 139 | Supports GIF, PNG, JPEG, and WEBP. |
||
| 140 | |||
| 141 | Parameters |
||
| 142 | ---------- |
||
| 143 | img: :class:`~pil:PIL.Image.Image` |
||
| 144 | Pillow image object. |
||
| 145 | filename: |
||
| 146 | The filename to be used when uploaded to discord. The extension is |
||
| 147 | used as image_format unless otherwise specified. |
||
| 148 | image_format: |
||
| 149 | The image_format to be used if you want to override the file |
||
| 150 | extension. |
||
| 151 | |||
| 152 | Returns |
||
| 153 | ------- |
||
| 154 | :class:`~pincer.objects.message.file.File` |
||
| 155 | The new file object. |
||
| 156 | |||
| 157 | Raises |
||
| 158 | ------ |
||
| 159 | ModuleNotFoundError: |
||
| 160 | ``Pillow`` is not installed |
||
| 161 | """ |
||
| 162 | if not PILLOW_IMPORT: |
||
| 163 | raise ModuleNotFoundError( |
||
| 164 | "The `Pillow` library is required for sending and converting " |
||
| 165 | "pillow images," |
||
| 166 | ) |
||
| 167 | |||
| 168 | if image_format is None: |
||
| 169 | image_format = _get_file_extension(filename) |
||
| 170 | |||
| 171 | if image_format == "jpg": |
||
| 172 | image_format = "jpeg" |
||
| 173 | |||
| 174 | # https://stackoverflow.com/questions/33101935/convert-pil-image-to-byte-array |
||
| 175 | # Credit goes to second answer |
||
| 176 | img_byte_arr = BytesIO() |
||
| 177 | img.save(img_byte_arr, format=image_format) |
||
| 178 | img_bytes = img_byte_arr.getvalue() |
||
| 179 | |||
| 180 | return cls( |
||
| 181 | content=img_bytes, image_format=image_format, filename=filename |
||
| 182 | ) |
||
| 206 |