simetri.image.image
1from typing import Any, Optional, Union, Callable, Tuple, Dict, List, Sequence 2 3from PIL import Image as PIL_Image 4from ..graphics.core import Base 5 6 7def supported_formats() -> List[str]: 8 """Generates a list of supported image formats available in your system. 9 Returns: 10 List[str]: A list of supported image formats available in your system. 11 """ 12 13 exts = PIL_Image.registered_extensions() 14 supported = {ex for ex, f in exts.items() if f in PIL_Image.OPEN} 15 16 return sorted(supported) 17 18from PIL import Image 19 20def convert_png_to_ico(png_path, ico_path, sizes=None): 21 """Converts a PNG image to an ICO file. 22 23 Args: 24 png_path: Path to the input PNG image. 25 ico_path: Path to save the output ICO file. 26 sizes: A list of tuples specifying the sizes to include in the ICO file, 27 e.g., [(16, 16), (32, 32), (48, 48)]. If None, defaults to [(32, 32)]. 28 """ 29 if sizes is None: 30 sizes = [(32, 32)] 31 32 img = Image.open(png_path) 33 34 icon_sizes = [] 35 for size in sizes: 36 icon_sizes.append(size) 37 38 img.save(ico_path, sizes=icon_sizes) 39 40 # Example usage: 41 convert_png_to_ico("input.png", "output.ico", sizes=[(16, 16), (32, 32)]) 42 43class Image(PIL_Image.Image, Base): 44 """ 45 A class that extends the PIL Image class to add additional functionality. 46 """ 47 48 def __init__(self, *args, **kwargs): 49 """ 50 Initialize an Image object. 51 52 Args: 53 *args: Variable length argument list. 54 **kwargs: Arbitrary keyword arguments. 55 """ 56 super().__init__(*args, **kwargs) 57 58 def __repr__(self): 59 """ 60 Return a string representation of the Image object. 61 62 Returns: 63 str: A string representation of the Image object. 64 """ 65 return f"Image({self.size}, {self.mode})" 66 67 def __str__(self): 68 """ 69 Return a human-readable string representation of the Image object. 70 71 Returns: 72 str: A human-readable string representation of the Image object. 73 """ 74 return f"Image of size {self.size} and mode {self.mode}" 75 76 @property 77 def filename(self) -> str: 78 """ 79 The filename of the image, if available. 80 81 Returns: 82 str: The filename of the image or None if not set. 83 """ 84 return self.info.get("filename", None) 85 86 @property 87 def format(self) -> str: 88 """ 89 The format of the image, if available. 90 91 Returns: 92 str: The format of the image (e.g., "JPEG", "PNG") or None if not set. 93 """ 94 return super().format 95 96 @property 97 def mode(self) -> str: 98 """ 99 The mode of the image. 100 101 Returns: 102 str: The mode of the image (e.g., "RGB", "L"). 103 """ 104 return super().mode 105 106 @property 107 def size(self) -> tuple: 108 """ 109 The size of the image. 110 111 Returns: 112 tuple: A tuple (width, height) representing the dimensions of the image in pixels. 113 """ 114 return super().size 115 116 @property 117 def width(self) -> int: 118 """ 119 The width of the image. 120 121 Returns: 122 int: The width of the image in pixels. 123 """ 124 return self.size[0] 125 126 @property 127 def height(self) -> int: 128 """ 129 The height of the image. 130 131 Returns: 132 int: The height of the image in pixels. 133 """ 134 return self.size[1] 135 136 @property 137 def info(self) -> dict: 138 """ 139 A dictionary containing miscellaneous information about the image. 140 141 Returns: 142 dict: A dictionary of metadata associated with the image. 143 """ 144 return super().info 145 146 @property 147 def palette(self): 148 """ 149 The palette of the image, if available. 150 151 Returns: 152 ImagePalette: The palette of the image or None if not applicable. 153 """ 154 return super().palette 155 156 @property 157 def category(self) -> str: 158 """ 159 The category of the image. 160 161 Returns: 162 str: The category of the image (e.g., "image"). 163 """ 164 return super().category 165 166 @property 167 def readonly(self) -> bool: 168 """ 169 Whether the image is read-only. 170 171 Returns: 172 bool: True if the image is read-only, False otherwise. 173 """ 174 return super().readonly 175 176 @property 177 def decoderconfig(self) -> tuple: 178 """ 179 The decoder configuration of the image. 180 181 Returns: 182 tuple: A tuple containing the decoder configuration. 183 """ 184 return super().decoderconfig 185 186 @property 187 def decodermaxblock(self) -> int: 188 """ 189 The maximum block size used by the decoder. 190 191 Returns: 192 int: The maximum block size in bytes. 193 """ 194 return super().decodermaxblock 195 196 def alpha_composite(self, im: 'Image', dest: Sequence[int] = (0, 0), 197 source: Sequence[int] = (0, 0)) -> 'Image': 198 """ 199 Blend two images together using alpha compositing. 200 This method is a wrapper around the PIL alpha_composite method. 201 202 Args: 203 im (Image): The source image to composite with. 204 dest (Sequence[int], optional): The destination coordinates. Defaults to (0, 0). 205 source (Sequence[int], optional): The source coordinates. Defaults to (0, 0). 206 207 Returns: 208 Image: The resulting image after alpha compositing. 209 """ 210 return super().alpha_composite(im, dest, source) 211 212 def apply_transparency(self) -> None: 213 """ 214 Apply transparency to the image. 215 216 This method is a wrapper around the PIL apply_transparency method. 217 """ 218 return super().apply_transparency() 219 220 def convert(self, mode=None, matrix=None, dither=None, palette=0, colors=256): 221 """ 222 Converts an image to a different mode. 223 224 Args: 225 mode (str, optional): The requested mode. See: :ref:`concept-modes`. 226 matrix (list, optional): An optional conversion matrix. 227 dither (int, optional): Dithering method, used when converting from mode "RGB" to "P" or from "RGB" or "L" to "1". 228 palette (int, optional): Palette to use when converting from mode "RGB" to "P". 229 colors (int, optional): Number of colors to use for the palette. 230 231 Returns: 232 Image: An Image object. 233 """ 234 return super().convert(mode, matrix, dither, palette, colors) 235 236 def copy(self): 237 """ 238 Copies this image. Use this method if you wish to paste things into an image, but still retain the original. 239 240 Returns: 241 Image: An Image object. 242 """ 243 return super().copy() 244 245 def crop(self, box=None): 246 """ 247 Returns a rectangular region from this image. The box is a 4-tuple defining the left, upper, right, and lower pixel coordinate. 248 249 Args: 250 box (tuple, optional): The crop rectangle, as a (left, upper, right, lower)-tuple. 251 252 Returns: 253 Image: An Image object. 254 """ 255 return super().crop(box) 256 257 def draft(self, mode, size): 258 """ 259 Configures the image file loader so it returns a version of the image that as closely as possible matches the given mode and size. 260 261 Args: 262 mode (str): The requested mode. 263 size (tuple): The requested size. 264 265 Returns: 266 None 267 """ 268 return super().draft(mode, size) 269 270 def effect_spread(self, distance): 271 """ 272 Randomly spreads pixels in an image. 273 274 Args: 275 distance (int): Distance to spread pixels. 276 277 Returns: 278 Image: An Image object. 279 """ 280 return super().effect_spread(distance) 281 282 def filter(self, filter): 283 """ 284 Applies the given filter to this image. 285 286 Args: 287 filter (Filter): Filter kernel. 288 289 Returns: 290 Image: An Image object. 291 """ 292 return super().filter(filter) 293 294 def getbands(self): 295 """ 296 Returns a tuple containing the name of each band in this image. For example, "RGB" returns ("R", "G", "B"). 297 298 Returns: 299 tuple: A tuple containing band names. 300 """ 301 return super().getbands() 302 303 def getbbox(self): 304 """ 305 Calculates the bounding box of the non-zero regions in the image. 306 307 Returns: 308 tuple: The bounding box is returned as a 4-tuple defining the left, upper, right, and lower pixel coordinate. 309 """ 310 return super().getbbox() 311 312 def getcolors(self, maxcolors=256): 313 """ 314 Returns a list of colors used in this image. 315 316 Args: 317 maxcolors (int, optional): Maximum number of colors. If this number is exceeded, this method stops counting and returns None. 318 319 Returns: 320 list: A list of (count, pixel) values. 321 """ 322 return super().getcolors(maxcolors) 323 324 def getdata(self, band=None): 325 """ 326 Returns the contents of this image as a sequence object containing pixel values. 327 328 Args: 329 band (int, optional): What band to return. Default is None. 330 331 Returns: 332 Sequence: Pixel values. 333 """ 334 return super().getdata(band) 335 336 def getextrema(self): 337 """ 338 Gets the minimum and maximum pixel values for each band in the image. 339 340 Returns: 341 tuple: A tuple containing one (min, max) tuple for each band. 342 """ 343 return super().getextrema() 344 345 def getpixel(self, xy): 346 """ 347 Returns the pixel value at a given position. 348 349 Args: 350 xy (tuple): The coordinate, given as (x, y). 351 352 Returns: 353 Pixel: The pixel value. 354 """ 355 return super().getpixel(xy) 356 357 def histogram(self, mask=None, extrema=None): 358 """ 359 Returns a histogram for the image. 360 361 Args: 362 mask (Image, optional): A mask image. 363 extrema (tuple, optional): A tuple of manually-specified extrema. 364 365 Returns: 366 list: A list containing pixel counts. 367 """ 368 return super().histogram(mask, extrema) 369 370 def paste(self, im, box=None, mask=None): 371 """ 372 Pastes another image into this image. 373 374 Args: 375 im (Image or tuple): The source image or pixel value. 376 box (tuple, optional): A 2-tuple giving the upper left corner, or a 4-tuple defining the left, upper, right, and lower pixel coordinate. 377 mask (Image, optional): A mask image. 378 379 Returns: 380 None 381 """ 382 return super().paste(im, box, mask) 383 384 def resize(self, size, resample=None, box=None, reducing_gap=None): 385 """ 386 Returns a resized copy of this image. 387 388 Args: 389 size (tuple): The requested size in pixels, as a 2-tuple. 390 resample (int, optional): An optional resampling filter. 391 box (tuple, optional): A box to define the region to resize. 392 reducing_gap (float, optional): Apply optimization by resizing the image in two steps. 393 394 Returns: 395 Image: An Image object. 396 """ 397 return super().resize(size, resample, box, reducing_gap) 398 399 def rotate(self, angle, resample=0, expand=0, center=None, translate=None, fillcolor=None): 400 """ 401 Returns a rotated copy of this image. 402 403 Args: 404 angle (float): The angle to rotate the image. 405 resample (int, optional): An optional resampling filter. 406 expand (int, optional): Optional expansion flag. 407 center (tuple, optional): Optional center of rotation. 408 translate (tuple, optional): An optional post-rotate translation. 409 fillcolor (tuple, optional): Optional fill color for the area outside the rotated image. 410 411 Returns: 412 Image: An Image object. 413 """ 414 return super().rotate(angle, resample, expand, center, translate, fillcolor) 415 416 def save(self, fp, format=None, **params): 417 """ 418 Saves this image under the given filename. 419 420 Args: 421 fp (str or file object): A filename (string) or file object. 422 format (str, optional): Optional format override. 423 **params: Extra parameters to the image writer. 424 425 Returns: 426 None 427 """ 428 return super().save(fp, format, **params) 429 430 def show(self, title=None, command=None): 431 """ 432 Displays this image. 433 434 Args: 435 title (str, optional): Optional title for the image window. 436 command (str, optional): Command used to show the image. 437 438 Returns: 439 None 440 """ 441 return super().show(title, command) 442 443 def split(self): 444 """ 445 Splits this image into individual bands. 446 447 Returns: 448 tuple: A tuple containing individual bands as Image objects. 449 """ 450 return super().split() 451 452 def transpose(self, method): 453 """ 454 Transposes this image. 455 456 Args: 457 method (int): One of the transpose methods. 458 459 Returns: 460 Image: An Image object. 461 """ 462 return super().transpose(method) 463 464open = PIL_Image.open 465alpha_composite = PIL_Image.alpha_composite 466blend = PIL_Image.blend 467composite = PIL_Image.composite 468eval = PIL_Image.eval 469merge = PIL_Image.merge 470new = PIL_Image.new 471# fromarrow = PIL_Image.fromarrow 472frombytes = PIL_Image.frombytes 473frombuffer = PIL_Image.frombuffer 474fromarray = PIL_Image.fromarray 475effect_mandelbrot = PIL_Image.effect_mandelbrot 476effect_noise = PIL_Image.effect_noise 477linear_gradient = PIL_Image.linear_gradient 478radial_gradient = PIL_Image.radial_gradient 479register_open = PIL_Image.register_open 480register_mime = PIL_Image.register_mime 481register_save = PIL_Image.register_save 482register_save_all = PIL_Image.register_save_all 483register_extension = PIL_Image.register_extension 484register_extensions = PIL_Image.register_extensions 485registered_extensions = PIL_Image.registered_extensions 486register_decoder = PIL_Image.register_decoder 487register_encoder = PIL_Image.register_encoder
8def supported_formats() -> List[str]: 9 """Generates a list of supported image formats available in your system. 10 Returns: 11 List[str]: A list of supported image formats available in your system. 12 """ 13 14 exts = PIL_Image.registered_extensions() 15 supported = {ex for ex, f in exts.items() if f in PIL_Image.OPEN} 16 17 return sorted(supported)
Generates a list of supported image formats available in your system.
Returns:
List[str]: A list of supported image formats available in your system.
21def convert_png_to_ico(png_path, ico_path, sizes=None): 22 """Converts a PNG image to an ICO file. 23 24 Args: 25 png_path: Path to the input PNG image. 26 ico_path: Path to save the output ICO file. 27 sizes: A list of tuples specifying the sizes to include in the ICO file, 28 e.g., [(16, 16), (32, 32), (48, 48)]. If None, defaults to [(32, 32)]. 29 """ 30 if sizes is None: 31 sizes = [(32, 32)] 32 33 img = Image.open(png_path) 34 35 icon_sizes = [] 36 for size in sizes: 37 icon_sizes.append(size) 38 39 img.save(ico_path, sizes=icon_sizes) 40 41 # Example usage: 42 convert_png_to_ico("input.png", "output.ico", sizes=[(16, 16), (32, 32)])
Converts a PNG image to an ICO file.
Arguments:
- png_path: Path to the input PNG image.
- ico_path: Path to save the output ICO file.
- sizes: A list of tuples specifying the sizes to include in the ICO file, e.g., [(16, 16), (32, 32), (48, 48)]. If None, defaults to [(32, 32)].
44class Image(PIL_Image.Image, Base): 45 """ 46 A class that extends the PIL Image class to add additional functionality. 47 """ 48 49 def __init__(self, *args, **kwargs): 50 """ 51 Initialize an Image object. 52 53 Args: 54 *args: Variable length argument list. 55 **kwargs: Arbitrary keyword arguments. 56 """ 57 super().__init__(*args, **kwargs) 58 59 def __repr__(self): 60 """ 61 Return a string representation of the Image object. 62 63 Returns: 64 str: A string representation of the Image object. 65 """ 66 return f"Image({self.size}, {self.mode})" 67 68 def __str__(self): 69 """ 70 Return a human-readable string representation of the Image object. 71 72 Returns: 73 str: A human-readable string representation of the Image object. 74 """ 75 return f"Image of size {self.size} and mode {self.mode}" 76 77 @property 78 def filename(self) -> str: 79 """ 80 The filename of the image, if available. 81 82 Returns: 83 str: The filename of the image or None if not set. 84 """ 85 return self.info.get("filename", None) 86 87 @property 88 def format(self) -> str: 89 """ 90 The format of the image, if available. 91 92 Returns: 93 str: The format of the image (e.g., "JPEG", "PNG") or None if not set. 94 """ 95 return super().format 96 97 @property 98 def mode(self) -> str: 99 """ 100 The mode of the image. 101 102 Returns: 103 str: The mode of the image (e.g., "RGB", "L"). 104 """ 105 return super().mode 106 107 @property 108 def size(self) -> tuple: 109 """ 110 The size of the image. 111 112 Returns: 113 tuple: A tuple (width, height) representing the dimensions of the image in pixels. 114 """ 115 return super().size 116 117 @property 118 def width(self) -> int: 119 """ 120 The width of the image. 121 122 Returns: 123 int: The width of the image in pixels. 124 """ 125 return self.size[0] 126 127 @property 128 def height(self) -> int: 129 """ 130 The height of the image. 131 132 Returns: 133 int: The height of the image in pixels. 134 """ 135 return self.size[1] 136 137 @property 138 def info(self) -> dict: 139 """ 140 A dictionary containing miscellaneous information about the image. 141 142 Returns: 143 dict: A dictionary of metadata associated with the image. 144 """ 145 return super().info 146 147 @property 148 def palette(self): 149 """ 150 The palette of the image, if available. 151 152 Returns: 153 ImagePalette: The palette of the image or None if not applicable. 154 """ 155 return super().palette 156 157 @property 158 def category(self) -> str: 159 """ 160 The category of the image. 161 162 Returns: 163 str: The category of the image (e.g., "image"). 164 """ 165 return super().category 166 167 @property 168 def readonly(self) -> bool: 169 """ 170 Whether the image is read-only. 171 172 Returns: 173 bool: True if the image is read-only, False otherwise. 174 """ 175 return super().readonly 176 177 @property 178 def decoderconfig(self) -> tuple: 179 """ 180 The decoder configuration of the image. 181 182 Returns: 183 tuple: A tuple containing the decoder configuration. 184 """ 185 return super().decoderconfig 186 187 @property 188 def decodermaxblock(self) -> int: 189 """ 190 The maximum block size used by the decoder. 191 192 Returns: 193 int: The maximum block size in bytes. 194 """ 195 return super().decodermaxblock 196 197 def alpha_composite(self, im: 'Image', dest: Sequence[int] = (0, 0), 198 source: Sequence[int] = (0, 0)) -> 'Image': 199 """ 200 Blend two images together using alpha compositing. 201 This method is a wrapper around the PIL alpha_composite method. 202 203 Args: 204 im (Image): The source image to composite with. 205 dest (Sequence[int], optional): The destination coordinates. Defaults to (0, 0). 206 source (Sequence[int], optional): The source coordinates. Defaults to (0, 0). 207 208 Returns: 209 Image: The resulting image after alpha compositing. 210 """ 211 return super().alpha_composite(im, dest, source) 212 213 def apply_transparency(self) -> None: 214 """ 215 Apply transparency to the image. 216 217 This method is a wrapper around the PIL apply_transparency method. 218 """ 219 return super().apply_transparency() 220 221 def convert(self, mode=None, matrix=None, dither=None, palette=0, colors=256): 222 """ 223 Converts an image to a different mode. 224 225 Args: 226 mode (str, optional): The requested mode. See: :ref:`concept-modes`. 227 matrix (list, optional): An optional conversion matrix. 228 dither (int, optional): Dithering method, used when converting from mode "RGB" to "P" or from "RGB" or "L" to "1". 229 palette (int, optional): Palette to use when converting from mode "RGB" to "P". 230 colors (int, optional): Number of colors to use for the palette. 231 232 Returns: 233 Image: An Image object. 234 """ 235 return super().convert(mode, matrix, dither, palette, colors) 236 237 def copy(self): 238 """ 239 Copies this image. Use this method if you wish to paste things into an image, but still retain the original. 240 241 Returns: 242 Image: An Image object. 243 """ 244 return super().copy() 245 246 def crop(self, box=None): 247 """ 248 Returns a rectangular region from this image. The box is a 4-tuple defining the left, upper, right, and lower pixel coordinate. 249 250 Args: 251 box (tuple, optional): The crop rectangle, as a (left, upper, right, lower)-tuple. 252 253 Returns: 254 Image: An Image object. 255 """ 256 return super().crop(box) 257 258 def draft(self, mode, size): 259 """ 260 Configures the image file loader so it returns a version of the image that as closely as possible matches the given mode and size. 261 262 Args: 263 mode (str): The requested mode. 264 size (tuple): The requested size. 265 266 Returns: 267 None 268 """ 269 return super().draft(mode, size) 270 271 def effect_spread(self, distance): 272 """ 273 Randomly spreads pixels in an image. 274 275 Args: 276 distance (int): Distance to spread pixels. 277 278 Returns: 279 Image: An Image object. 280 """ 281 return super().effect_spread(distance) 282 283 def filter(self, filter): 284 """ 285 Applies the given filter to this image. 286 287 Args: 288 filter (Filter): Filter kernel. 289 290 Returns: 291 Image: An Image object. 292 """ 293 return super().filter(filter) 294 295 def getbands(self): 296 """ 297 Returns a tuple containing the name of each band in this image. For example, "RGB" returns ("R", "G", "B"). 298 299 Returns: 300 tuple: A tuple containing band names. 301 """ 302 return super().getbands() 303 304 def getbbox(self): 305 """ 306 Calculates the bounding box of the non-zero regions in the image. 307 308 Returns: 309 tuple: The bounding box is returned as a 4-tuple defining the left, upper, right, and lower pixel coordinate. 310 """ 311 return super().getbbox() 312 313 def getcolors(self, maxcolors=256): 314 """ 315 Returns a list of colors used in this image. 316 317 Args: 318 maxcolors (int, optional): Maximum number of colors. If this number is exceeded, this method stops counting and returns None. 319 320 Returns: 321 list: A list of (count, pixel) values. 322 """ 323 return super().getcolors(maxcolors) 324 325 def getdata(self, band=None): 326 """ 327 Returns the contents of this image as a sequence object containing pixel values. 328 329 Args: 330 band (int, optional): What band to return. Default is None. 331 332 Returns: 333 Sequence: Pixel values. 334 """ 335 return super().getdata(band) 336 337 def getextrema(self): 338 """ 339 Gets the minimum and maximum pixel values for each band in the image. 340 341 Returns: 342 tuple: A tuple containing one (min, max) tuple for each band. 343 """ 344 return super().getextrema() 345 346 def getpixel(self, xy): 347 """ 348 Returns the pixel value at a given position. 349 350 Args: 351 xy (tuple): The coordinate, given as (x, y). 352 353 Returns: 354 Pixel: The pixel value. 355 """ 356 return super().getpixel(xy) 357 358 def histogram(self, mask=None, extrema=None): 359 """ 360 Returns a histogram for the image. 361 362 Args: 363 mask (Image, optional): A mask image. 364 extrema (tuple, optional): A tuple of manually-specified extrema. 365 366 Returns: 367 list: A list containing pixel counts. 368 """ 369 return super().histogram(mask, extrema) 370 371 def paste(self, im, box=None, mask=None): 372 """ 373 Pastes another image into this image. 374 375 Args: 376 im (Image or tuple): The source image or pixel value. 377 box (tuple, optional): A 2-tuple giving the upper left corner, or a 4-tuple defining the left, upper, right, and lower pixel coordinate. 378 mask (Image, optional): A mask image. 379 380 Returns: 381 None 382 """ 383 return super().paste(im, box, mask) 384 385 def resize(self, size, resample=None, box=None, reducing_gap=None): 386 """ 387 Returns a resized copy of this image. 388 389 Args: 390 size (tuple): The requested size in pixels, as a 2-tuple. 391 resample (int, optional): An optional resampling filter. 392 box (tuple, optional): A box to define the region to resize. 393 reducing_gap (float, optional): Apply optimization by resizing the image in two steps. 394 395 Returns: 396 Image: An Image object. 397 """ 398 return super().resize(size, resample, box, reducing_gap) 399 400 def rotate(self, angle, resample=0, expand=0, center=None, translate=None, fillcolor=None): 401 """ 402 Returns a rotated copy of this image. 403 404 Args: 405 angle (float): The angle to rotate the image. 406 resample (int, optional): An optional resampling filter. 407 expand (int, optional): Optional expansion flag. 408 center (tuple, optional): Optional center of rotation. 409 translate (tuple, optional): An optional post-rotate translation. 410 fillcolor (tuple, optional): Optional fill color for the area outside the rotated image. 411 412 Returns: 413 Image: An Image object. 414 """ 415 return super().rotate(angle, resample, expand, center, translate, fillcolor) 416 417 def save(self, fp, format=None, **params): 418 """ 419 Saves this image under the given filename. 420 421 Args: 422 fp (str or file object): A filename (string) or file object. 423 format (str, optional): Optional format override. 424 **params: Extra parameters to the image writer. 425 426 Returns: 427 None 428 """ 429 return super().save(fp, format, **params) 430 431 def show(self, title=None, command=None): 432 """ 433 Displays this image. 434 435 Args: 436 title (str, optional): Optional title for the image window. 437 command (str, optional): Command used to show the image. 438 439 Returns: 440 None 441 """ 442 return super().show(title, command) 443 444 def split(self): 445 """ 446 Splits this image into individual bands. 447 448 Returns: 449 tuple: A tuple containing individual bands as Image objects. 450 """ 451 return super().split() 452 453 def transpose(self, method): 454 """ 455 Transposes this image. 456 457 Args: 458 method (int): One of the transpose methods. 459 460 Returns: 461 Image: An Image object. 462 """ 463 return super().transpose(method)
A class that extends the PIL Image class to add additional functionality.
49 def __init__(self, *args, **kwargs): 50 """ 51 Initialize an Image object. 52 53 Args: 54 *args: Variable length argument list. 55 **kwargs: Arbitrary keyword arguments. 56 """ 57 super().__init__(*args, **kwargs)
Initialize an Image object.
Arguments:
- *args: Variable length argument list.
- **kwargs: Arbitrary keyword arguments.
77 @property 78 def filename(self) -> str: 79 """ 80 The filename of the image, if available. 81 82 Returns: 83 str: The filename of the image or None if not set. 84 """ 85 return self.info.get("filename", None)
The filename of the image, if available.
Returns:
str: The filename of the image or None if not set.
87 @property 88 def format(self) -> str: 89 """ 90 The format of the image, if available. 91 92 Returns: 93 str: The format of the image (e.g., "JPEG", "PNG") or None if not set. 94 """ 95 return super().format
The format of the image, if available.
Returns:
str: The format of the image (e.g., "JPEG", "PNG") or None if not set.
97 @property 98 def mode(self) -> str: 99 """ 100 The mode of the image. 101 102 Returns: 103 str: The mode of the image (e.g., "RGB", "L"). 104 """ 105 return super().mode
The mode of the image.
Returns:
str: The mode of the image (e.g., "RGB", "L").
107 @property 108 def size(self) -> tuple: 109 """ 110 The size of the image. 111 112 Returns: 113 tuple: A tuple (width, height) representing the dimensions of the image in pixels. 114 """ 115 return super().size
The size of the image.
Returns:
tuple: A tuple (width, height) representing the dimensions of the image in pixels.
117 @property 118 def width(self) -> int: 119 """ 120 The width of the image. 121 122 Returns: 123 int: The width of the image in pixels. 124 """ 125 return self.size[0]
The width of the image.
Returns:
int: The width of the image in pixels.
127 @property 128 def height(self) -> int: 129 """ 130 The height of the image. 131 132 Returns: 133 int: The height of the image in pixels. 134 """ 135 return self.size[1]
The height of the image.
Returns:
int: The height of the image in pixels.
137 @property 138 def info(self) -> dict: 139 """ 140 A dictionary containing miscellaneous information about the image. 141 142 Returns: 143 dict: A dictionary of metadata associated with the image. 144 """ 145 return super().info
A dictionary containing miscellaneous information about the image.
Returns:
dict: A dictionary of metadata associated with the image.
147 @property 148 def palette(self): 149 """ 150 The palette of the image, if available. 151 152 Returns: 153 ImagePalette: The palette of the image or None if not applicable. 154 """ 155 return super().palette
The palette of the image, if available.
Returns:
ImagePalette: The palette of the image or None if not applicable.
157 @property 158 def category(self) -> str: 159 """ 160 The category of the image. 161 162 Returns: 163 str: The category of the image (e.g., "image"). 164 """ 165 return super().category
The category of the image.
Returns:
str: The category of the image (e.g., "image").
167 @property 168 def readonly(self) -> bool: 169 """ 170 Whether the image is read-only. 171 172 Returns: 173 bool: True if the image is read-only, False otherwise. 174 """ 175 return super().readonly
Whether the image is read-only.
Returns:
bool: True if the image is read-only, False otherwise.
177 @property 178 def decoderconfig(self) -> tuple: 179 """ 180 The decoder configuration of the image. 181 182 Returns: 183 tuple: A tuple containing the decoder configuration. 184 """ 185 return super().decoderconfig
The decoder configuration of the image.
Returns:
tuple: A tuple containing the decoder configuration.
187 @property 188 def decodermaxblock(self) -> int: 189 """ 190 The maximum block size used by the decoder. 191 192 Returns: 193 int: The maximum block size in bytes. 194 """ 195 return super().decodermaxblock
The maximum block size used by the decoder.
Returns:
int: The maximum block size in bytes.
197 def alpha_composite(self, im: 'Image', dest: Sequence[int] = (0, 0), 198 source: Sequence[int] = (0, 0)) -> 'Image': 199 """ 200 Blend two images together using alpha compositing. 201 This method is a wrapper around the PIL alpha_composite method. 202 203 Args: 204 im (Image): The source image to composite with. 205 dest (Sequence[int], optional): The destination coordinates. Defaults to (0, 0). 206 source (Sequence[int], optional): The source coordinates. Defaults to (0, 0). 207 208 Returns: 209 Image: The resulting image after alpha compositing. 210 """ 211 return super().alpha_composite(im, dest, source)
Blend two images together using alpha compositing. This method is a wrapper around the PIL alpha_composite method.
Arguments:
- im (Image): The source image to composite with.
- dest (Sequence[int], optional): The destination coordinates. Defaults to (0, 0).
- source (Sequence[int], optional): The source coordinates. Defaults to (0, 0).
Returns:
Image: The resulting image after alpha compositing.
213 def apply_transparency(self) -> None: 214 """ 215 Apply transparency to the image. 216 217 This method is a wrapper around the PIL apply_transparency method. 218 """ 219 return super().apply_transparency()
Apply transparency to the image.
This method is a wrapper around the PIL apply_transparency method.
221 def convert(self, mode=None, matrix=None, dither=None, palette=0, colors=256): 222 """ 223 Converts an image to a different mode. 224 225 Args: 226 mode (str, optional): The requested mode. See: :ref:`concept-modes`. 227 matrix (list, optional): An optional conversion matrix. 228 dither (int, optional): Dithering method, used when converting from mode "RGB" to "P" or from "RGB" or "L" to "1". 229 palette (int, optional): Palette to use when converting from mode "RGB" to "P". 230 colors (int, optional): Number of colors to use for the palette. 231 232 Returns: 233 Image: An Image object. 234 """ 235 return super().convert(mode, matrix, dither, palette, colors)
Converts an image to a different mode.
Arguments:
- mode (str, optional): The requested mode. See: :ref:
concept-modes
. - matrix (list, optional): An optional conversion matrix.
- dither (int, optional): Dithering method, used when converting from mode "RGB" to "P" or from "RGB" or "L" to "1".
- palette (int, optional): Palette to use when converting from mode "RGB" to "P".
- colors (int, optional): Number of colors to use for the palette.
Returns:
Image: An Image object.
237 def copy(self): 238 """ 239 Copies this image. Use this method if you wish to paste things into an image, but still retain the original. 240 241 Returns: 242 Image: An Image object. 243 """ 244 return super().copy()
Copies this image. Use this method if you wish to paste things into an image, but still retain the original.
Returns:
Image: An Image object.
246 def crop(self, box=None): 247 """ 248 Returns a rectangular region from this image. The box is a 4-tuple defining the left, upper, right, and lower pixel coordinate. 249 250 Args: 251 box (tuple, optional): The crop rectangle, as a (left, upper, right, lower)-tuple. 252 253 Returns: 254 Image: An Image object. 255 """ 256 return super().crop(box)
Returns a rectangular region from this image. The box is a 4-tuple defining the left, upper, right, and lower pixel coordinate.
Arguments:
- box (tuple, optional): The crop rectangle, as a (left, upper, right, lower)-tuple.
Returns:
Image: An Image object.
258 def draft(self, mode, size): 259 """ 260 Configures the image file loader so it returns a version of the image that as closely as possible matches the given mode and size. 261 262 Args: 263 mode (str): The requested mode. 264 size (tuple): The requested size. 265 266 Returns: 267 None 268 """ 269 return super().draft(mode, size)
Configures the image file loader so it returns a version of the image that as closely as possible matches the given mode and size.
Arguments:
- mode (str): The requested mode.
- size (tuple): The requested size.
Returns:
None
271 def effect_spread(self, distance): 272 """ 273 Randomly spreads pixels in an image. 274 275 Args: 276 distance (int): Distance to spread pixels. 277 278 Returns: 279 Image: An Image object. 280 """ 281 return super().effect_spread(distance)
Randomly spreads pixels in an image.
Arguments:
- distance (int): Distance to spread pixels.
Returns:
Image: An Image object.
283 def filter(self, filter): 284 """ 285 Applies the given filter to this image. 286 287 Args: 288 filter (Filter): Filter kernel. 289 290 Returns: 291 Image: An Image object. 292 """ 293 return super().filter(filter)
Applies the given filter to this image.
Arguments:
- filter (Filter): Filter kernel.
Returns:
Image: An Image object.
295 def getbands(self): 296 """ 297 Returns a tuple containing the name of each band in this image. For example, "RGB" returns ("R", "G", "B"). 298 299 Returns: 300 tuple: A tuple containing band names. 301 """ 302 return super().getbands()
Returns a tuple containing the name of each band in this image. For example, "RGB" returns ("R", "G", "B").
Returns:
tuple: A tuple containing band names.
304 def getbbox(self): 305 """ 306 Calculates the bounding box of the non-zero regions in the image. 307 308 Returns: 309 tuple: The bounding box is returned as a 4-tuple defining the left, upper, right, and lower pixel coordinate. 310 """ 311 return super().getbbox()
Calculates the bounding box of the non-zero regions in the image.
Returns:
tuple: The bounding box is returned as a 4-tuple defining the left, upper, right, and lower pixel coordinate.
313 def getcolors(self, maxcolors=256): 314 """ 315 Returns a list of colors used in this image. 316 317 Args: 318 maxcolors (int, optional): Maximum number of colors. If this number is exceeded, this method stops counting and returns None. 319 320 Returns: 321 list: A list of (count, pixel) values. 322 """ 323 return super().getcolors(maxcolors)
Returns a list of colors used in this image.
Arguments:
- maxcolors (int, optional): Maximum number of colors. If this number is exceeded, this method stops counting and returns None.
Returns:
list: A list of (count, pixel) values.
325 def getdata(self, band=None): 326 """ 327 Returns the contents of this image as a sequence object containing pixel values. 328 329 Args: 330 band (int, optional): What band to return. Default is None. 331 332 Returns: 333 Sequence: Pixel values. 334 """ 335 return super().getdata(band)
Returns the contents of this image as a sequence object containing pixel values.
Arguments:
- band (int, optional): What band to return. Default is None.
Returns:
Sequence: Pixel values.
337 def getextrema(self): 338 """ 339 Gets the minimum and maximum pixel values for each band in the image. 340 341 Returns: 342 tuple: A tuple containing one (min, max) tuple for each band. 343 """ 344 return super().getextrema()
Gets the minimum and maximum pixel values for each band in the image.
Returns:
tuple: A tuple containing one (min, max) tuple for each band.
346 def getpixel(self, xy): 347 """ 348 Returns the pixel value at a given position. 349 350 Args: 351 xy (tuple): The coordinate, given as (x, y). 352 353 Returns: 354 Pixel: The pixel value. 355 """ 356 return super().getpixel(xy)
Returns the pixel value at a given position.
Arguments:
- xy (tuple): The coordinate, given as (x, y).
Returns:
Pixel: The pixel value.
358 def histogram(self, mask=None, extrema=None): 359 """ 360 Returns a histogram for the image. 361 362 Args: 363 mask (Image, optional): A mask image. 364 extrema (tuple, optional): A tuple of manually-specified extrema. 365 366 Returns: 367 list: A list containing pixel counts. 368 """ 369 return super().histogram(mask, extrema)
Returns a histogram for the image.
Arguments:
- mask (Image, optional): A mask image.
- extrema (tuple, optional): A tuple of manually-specified extrema.
Returns:
list: A list containing pixel counts.
371 def paste(self, im, box=None, mask=None): 372 """ 373 Pastes another image into this image. 374 375 Args: 376 im (Image or tuple): The source image or pixel value. 377 box (tuple, optional): A 2-tuple giving the upper left corner, or a 4-tuple defining the left, upper, right, and lower pixel coordinate. 378 mask (Image, optional): A mask image. 379 380 Returns: 381 None 382 """ 383 return super().paste(im, box, mask)
Pastes another image into this image.
Arguments:
- im (Image or tuple): The source image or pixel value.
- box (tuple, optional): A 2-tuple giving the upper left corner, or a 4-tuple defining the left, upper, right, and lower pixel coordinate.
- mask (Image, optional): A mask image.
Returns:
None
385 def resize(self, size, resample=None, box=None, reducing_gap=None): 386 """ 387 Returns a resized copy of this image. 388 389 Args: 390 size (tuple): The requested size in pixels, as a 2-tuple. 391 resample (int, optional): An optional resampling filter. 392 box (tuple, optional): A box to define the region to resize. 393 reducing_gap (float, optional): Apply optimization by resizing the image in two steps. 394 395 Returns: 396 Image: An Image object. 397 """ 398 return super().resize(size, resample, box, reducing_gap)
Returns a resized copy of this image.
Arguments:
- size (tuple): The requested size in pixels, as a 2-tuple.
- resample (int, optional): An optional resampling filter.
- box (tuple, optional): A box to define the region to resize.
- reducing_gap (float, optional): Apply optimization by resizing the image in two steps.
Returns:
Image: An Image object.
400 def rotate(self, angle, resample=0, expand=0, center=None, translate=None, fillcolor=None): 401 """ 402 Returns a rotated copy of this image. 403 404 Args: 405 angle (float): The angle to rotate the image. 406 resample (int, optional): An optional resampling filter. 407 expand (int, optional): Optional expansion flag. 408 center (tuple, optional): Optional center of rotation. 409 translate (tuple, optional): An optional post-rotate translation. 410 fillcolor (tuple, optional): Optional fill color for the area outside the rotated image. 411 412 Returns: 413 Image: An Image object. 414 """ 415 return super().rotate(angle, resample, expand, center, translate, fillcolor)
Returns a rotated copy of this image.
Arguments:
- angle (float): The angle to rotate the image.
- resample (int, optional): An optional resampling filter.
- expand (int, optional): Optional expansion flag.
- center (tuple, optional): Optional center of rotation.
- translate (tuple, optional): An optional post-rotate translation.
- fillcolor (tuple, optional): Optional fill color for the area outside the rotated image.
Returns:
Image: An Image object.
417 def save(self, fp, format=None, **params): 418 """ 419 Saves this image under the given filename. 420 421 Args: 422 fp (str or file object): A filename (string) or file object. 423 format (str, optional): Optional format override. 424 **params: Extra parameters to the image writer. 425 426 Returns: 427 None 428 """ 429 return super().save(fp, format, **params)
Saves this image under the given filename.
Arguments:
- fp (str or file object): A filename (string) or file object.
- format (str, optional): Optional format override.
- **params: Extra parameters to the image writer.
Returns:
None
431 def show(self, title=None, command=None): 432 """ 433 Displays this image. 434 435 Args: 436 title (str, optional): Optional title for the image window. 437 command (str, optional): Command used to show the image. 438 439 Returns: 440 None 441 """ 442 return super().show(title, command)
Displays this image.
Arguments:
- title (str, optional): Optional title for the image window.
- command (str, optional): Command used to show the image.
Returns:
None
444 def split(self): 445 """ 446 Splits this image into individual bands. 447 448 Returns: 449 tuple: A tuple containing individual bands as Image objects. 450 """ 451 return super().split()
Splits this image into individual bands.
Returns:
tuple: A tuple containing individual bands as Image objects.
453 def transpose(self, method): 454 """ 455 Transposes this image. 456 457 Args: 458 method (int): One of the transpose methods. 459 460 Returns: 461 Image: An Image object. 462 """ 463 return super().transpose(method)
Transposes this image.
Arguments:
- method (int): One of the transpose methods.
Returns:
Image: An Image object.
3410def open( 3411 fp: StrOrBytesPath | IO[bytes], 3412 mode: Literal["r"] = "r", 3413 formats: list[str] | tuple[str, ...] | None = None, 3414) -> ImageFile.ImageFile: 3415 """ 3416 Opens and identifies the given image file. 3417 3418 This is a lazy operation; this function identifies the file, but 3419 the file remains open and the actual image data is not read from 3420 the file until you try to process the data (or call the 3421 :py:meth:`~PIL.Image.Image.load` method). See 3422 :py:func:`~PIL.Image.new`. See :ref:`file-handling`. 3423 3424 :param fp: A filename (string), os.PathLike object or a file object. 3425 The file object must implement ``file.read``, 3426 ``file.seek``, and ``file.tell`` methods, 3427 and be opened in binary mode. The file object will also seek to zero 3428 before reading. 3429 :param mode: The mode. If given, this argument must be "r". 3430 :param formats: A list or tuple of formats to attempt to load the file in. 3431 This can be used to restrict the set of formats checked. 3432 Pass ``None`` to try all supported formats. You can print the set of 3433 available formats by running ``python3 -m PIL`` or using 3434 the :py:func:`PIL.features.pilinfo` function. 3435 :returns: An :py:class:`~PIL.Image.Image` object. 3436 :exception FileNotFoundError: If the file cannot be found. 3437 :exception PIL.UnidentifiedImageError: If the image cannot be opened and 3438 identified. 3439 :exception ValueError: If the ``mode`` is not "r", or if a ``StringIO`` 3440 instance is used for ``fp``. 3441 :exception TypeError: If ``formats`` is not ``None``, a list or a tuple. 3442 """ 3443 3444 if mode != "r": 3445 msg = f"bad mode {repr(mode)}" # type: ignore[unreachable] 3446 raise ValueError(msg) 3447 elif isinstance(fp, io.StringIO): 3448 msg = ( # type: ignore[unreachable] 3449 "StringIO cannot be used to open an image. " 3450 "Binary data must be used instead." 3451 ) 3452 raise ValueError(msg) 3453 3454 if formats is None: 3455 formats = ID 3456 elif not isinstance(formats, (list, tuple)): 3457 msg = "formats must be a list or tuple" # type: ignore[unreachable] 3458 raise TypeError(msg) 3459 3460 exclusive_fp = False 3461 filename: str | bytes = "" 3462 if is_path(fp): 3463 filename = os.fspath(fp) 3464 3465 if filename: 3466 fp = builtins.open(filename, "rb") 3467 exclusive_fp = True 3468 else: 3469 fp = cast(IO[bytes], fp) 3470 3471 try: 3472 fp.seek(0) 3473 except (AttributeError, io.UnsupportedOperation): 3474 fp = io.BytesIO(fp.read()) 3475 exclusive_fp = True 3476 3477 prefix = fp.read(16) 3478 3479 preinit() 3480 3481 warning_messages: list[str] = [] 3482 3483 def _open_core( 3484 fp: IO[bytes], 3485 filename: str | bytes, 3486 prefix: bytes, 3487 formats: list[str] | tuple[str, ...], 3488 ) -> ImageFile.ImageFile | None: 3489 for i in formats: 3490 i = i.upper() 3491 if i not in OPEN: 3492 init() 3493 try: 3494 factory, accept = OPEN[i] 3495 result = not accept or accept(prefix) 3496 if isinstance(result, str): 3497 warning_messages.append(result) 3498 elif result: 3499 fp.seek(0) 3500 im = factory(fp, filename) 3501 _decompression_bomb_check(im.size) 3502 return im 3503 except (SyntaxError, IndexError, TypeError, struct.error) as e: 3504 if WARN_POSSIBLE_FORMATS: 3505 warning_messages.append(i + " opening failed. " + str(e)) 3506 except BaseException: 3507 if exclusive_fp: 3508 fp.close() 3509 raise 3510 return None 3511 3512 im = _open_core(fp, filename, prefix, formats) 3513 3514 if im is None and formats is ID: 3515 checked_formats = ID.copy() 3516 if init(): 3517 im = _open_core( 3518 fp, 3519 filename, 3520 prefix, 3521 tuple(format for format in formats if format not in checked_formats), 3522 ) 3523 3524 if im: 3525 im._exclusive_fp = exclusive_fp 3526 return im 3527 3528 if exclusive_fp: 3529 fp.close() 3530 for message in warning_messages: 3531 warnings.warn(message) 3532 msg = "cannot identify image file %r" % (filename if filename else fp) 3533 raise UnidentifiedImageError(msg)
Open an image file and return an Image object.
Arguments:
- fp: A file-like object or a string path to the image file.
- mode: The mode to open the image in. Default is 'r' (read).
- formats: A list of formats to try when opening the image.
Returns:
Image object.
3540def alpha_composite(im1: Image, im2: Image) -> Image: 3541 """ 3542 Alpha composite im2 over im1. 3543 3544 :param im1: The first image. Must have mode RGBA. 3545 :param im2: The second image. Must have mode RGBA, and the same size as 3546 the first image. 3547 :returns: An :py:class:`~PIL.Image.Image` object. 3548 """ 3549 3550 im1.load() 3551 im2.load() 3552 return im1._new(core.alpha_composite(im1.im, im2.im))
Blend two images together using alpha compositing.
Arguments:
- im: The image to blend with.
- dest: The destination image. If None, a new image is created.
Returns:
The blended image.
3555def blend(im1: Image, im2: Image, alpha: float) -> Image: 3556 """ 3557 Creates a new image by interpolating between two input images, using 3558 a constant alpha:: 3559 3560 out = image1 * (1.0 - alpha) + image2 * alpha 3561 3562 :param im1: The first image. 3563 :param im2: The second image. Must have the same mode and size as 3564 the first image. 3565 :param alpha: The interpolation alpha factor. If alpha is 0.0, a 3566 copy of the first image is returned. If alpha is 1.0, a copy of 3567 the second image is returned. There are no restrictions on the 3568 alpha value. If necessary, the result is clipped to fit into 3569 the allowed output range. 3570 :returns: An :py:class:`~PIL.Image.Image` object. 3571 """ 3572 3573 im1.load() 3574 im2.load() 3575 return im1._new(core.blend(im1.im, im2.im, alpha))
Creates a new image by interpolating between two input images, using a constant alpha::
out = image1 * (1.0 - alpha) + image2 * alpha
Parameters
- im1: The first image.
- im2: The second image. Must have the same mode and size as the first image.
- alpha: The interpolation alpha factor. If alpha is 0.0, a
copy of the first image is returned. If alpha is 1.0, a copy of
the second image is returned. There are no restrictions on the
alpha value. If necessary, the result is clipped to fit into
the allowed output range.
:returns: An
~PIL.Image.Image
object.
3578def composite(image1: Image, image2: Image, mask: Image) -> Image: 3579 """ 3580 Create composite image by blending images using a transparency mask. 3581 3582 :param image1: The first image. 3583 :param image2: The second image. Must have the same mode and 3584 size as the first image. 3585 :param mask: A mask image. This image can have mode 3586 "1", "L", or "RGBA", and must have the same size as the 3587 other two images. 3588 """ 3589 3590 image = image2.copy() 3591 image.paste(image1, None, mask) 3592 return image
Composite two images together.
Arguments:
- im: The image to composite with.
- dest: The destination image. If None, a new image is created.
Returns:
The composited image.
3595def eval(image: Image, *args: Callable[[int], float]) -> Image: 3596 """ 3597 Applies the function (which should take one argument) to each pixel 3598 in the given image. If the image has more than one band, the same 3599 function is applied to each band. Note that the function is 3600 evaluated once for each possible pixel value, so you cannot use 3601 random components or other generators. 3602 3603 :param image: The input image. 3604 :param function: A function object, taking one integer argument. 3605 :returns: An :py:class:`~PIL.Image.Image` object. 3606 """ 3607 3608 return image.point(args[0])
Evaluate an expression on the image.
Arguments:
- expr: The expression to evaluate.
- channel_order: The order of the channels in the image.
Returns:
The evaluated image.
3611def merge(mode: str, bands: Sequence[Image]) -> Image: 3612 """ 3613 Merge a set of single band images into a new multiband image. 3614 3615 :param mode: The mode to use for the output image. See: 3616 :ref:`concept-modes`. 3617 :param bands: A sequence containing one single-band image for 3618 each band in the output image. All bands must have the 3619 same size. 3620 :returns: An :py:class:`~PIL.Image.Image` object. 3621 """ 3622 3623 if getmodebands(mode) != len(bands) or "*" in mode: 3624 msg = "wrong number of bands" 3625 raise ValueError(msg) 3626 for band in bands[1:]: 3627 if band.mode != getmodetype(mode): 3628 msg = "mode mismatch" 3629 raise ValueError(msg) 3630 if band.size != bands[0].size: 3631 msg = "size mismatch" 3632 raise ValueError(msg) 3633 for band in bands: 3634 band.load() 3635 return bands[0]._new(core.merge(mode, *[b.im for b in bands]))
Merge multiple images into one.
Arguments:
- mode: The mode to merge the images in.
- *args: The images to merge.
Returns:
The merged image.
3084def new( 3085 mode: str, 3086 size: tuple[int, int] | list[int], 3087 color: float | tuple[float, ...] | str | None = 0, 3088) -> Image: 3089 """ 3090 Creates a new image with the given mode and size. 3091 3092 :param mode: The mode to use for the new image. See: 3093 :ref:`concept-modes`. 3094 :param size: A 2-tuple, containing (width, height) in pixels. 3095 :param color: What color to use for the image. Default is black. 3096 If given, this should be a single integer or floating point value 3097 for single-band modes, and a tuple for multi-band modes (one value 3098 per band). When creating RGB or HSV images, you can also use color 3099 strings as supported by the ImageColor module. If the color is 3100 None, the image is not initialised. 3101 :returns: An :py:class:`~PIL.Image.Image` object. 3102 """ 3103 3104 if mode in ("BGR;15", "BGR;16", "BGR;24"): 3105 deprecate(mode, 12) 3106 3107 _check_size(size) 3108 3109 if color is None: 3110 # don't initialize 3111 return Image()._new(core.new(mode, size)) 3112 3113 if isinstance(color, str): 3114 # css3-style specifier 3115 3116 from . import ImageColor 3117 3118 color = ImageColor.getcolor(color, mode) 3119 3120 im = Image() 3121 if ( 3122 mode == "P" 3123 and isinstance(color, (list, tuple)) 3124 and all(isinstance(i, int) for i in color) 3125 ): 3126 color_ints: tuple[int, ...] = cast(tuple[int, ...], tuple(color)) 3127 if len(color_ints) == 3 or len(color_ints) == 4: 3128 # RGB or RGBA value for a P image 3129 from . import ImagePalette 3130 3131 im.palette = ImagePalette.ImagePalette() 3132 color = im.palette.getcolor(color_ints) 3133 return im._new(core.fill(mode, size, color))
Create a new image with the specified mode and size.
Arguments:
- mode: The mode of the image.
- size: The size of the image.
- color: The color to fill the image with. Default is 0 (black).
Returns:
A new Image object.
3136def frombytes( 3137 mode: str, 3138 size: tuple[int, int], 3139 data: bytes | bytearray | SupportsArrayInterface, 3140 decoder_name: str = "raw", 3141 *args: Any, 3142) -> Image: 3143 """ 3144 Creates a copy of an image memory from pixel data in a buffer. 3145 3146 In its simplest form, this function takes three arguments 3147 (mode, size, and unpacked pixel data). 3148 3149 You can also use any pixel decoder supported by PIL. For more 3150 information on available decoders, see the section 3151 :ref:`Writing Your Own File Codec <file-codecs>`. 3152 3153 Note that this function decodes pixel data only, not entire images. 3154 If you have an entire image in a string, wrap it in a 3155 :py:class:`~io.BytesIO` object, and use :py:func:`~PIL.Image.open` to load 3156 it. 3157 3158 :param mode: The image mode. See: :ref:`concept-modes`. 3159 :param size: The image size. 3160 :param data: A byte buffer containing raw data for the given mode. 3161 :param decoder_name: What decoder to use. 3162 :param args: Additional parameters for the given decoder. 3163 :returns: An :py:class:`~PIL.Image.Image` object. 3164 """ 3165 3166 _check_size(size) 3167 3168 im = new(mode, size) 3169 if im.width != 0 and im.height != 0: 3170 decoder_args: Any = args 3171 if len(decoder_args) == 1 and isinstance(decoder_args[0], tuple): 3172 # may pass tuple instead of argument list 3173 decoder_args = decoder_args[0] 3174 3175 if decoder_name == "raw" and decoder_args == (): 3176 decoder_args = mode 3177 3178 im.frombytes(data, decoder_name, decoder_args) 3179 return im
Create an image from bytes.
Arguments:
- mode: The mode of the image.
- size: The size of the image.
- data: The byte data to create the image from.
- decoder_name: The name of the decoder to use. Default is 'raw'.
Returns:
A new Image object.
3182def frombuffer( 3183 mode: str, 3184 size: tuple[int, int], 3185 data: bytes | SupportsArrayInterface, 3186 decoder_name: str = "raw", 3187 *args: Any, 3188) -> Image: 3189 """ 3190 Creates an image memory referencing pixel data in a byte buffer. 3191 3192 This function is similar to :py:func:`~PIL.Image.frombytes`, but uses data 3193 in the byte buffer, where possible. This means that changes to the 3194 original buffer object are reflected in this image). Not all modes can 3195 share memory; supported modes include "L", "RGBX", "RGBA", and "CMYK". 3196 3197 Note that this function decodes pixel data only, not entire images. 3198 If you have an entire image file in a string, wrap it in a 3199 :py:class:`~io.BytesIO` object, and use :py:func:`~PIL.Image.open` to load it. 3200 3201 The default parameters used for the "raw" decoder differs from that used for 3202 :py:func:`~PIL.Image.frombytes`. This is a bug, and will probably be fixed in a 3203 future release. The current release issues a warning if you do this; to disable 3204 the warning, you should provide the full set of parameters. See below for details. 3205 3206 :param mode: The image mode. See: :ref:`concept-modes`. 3207 :param size: The image size. 3208 :param data: A bytes or other buffer object containing raw 3209 data for the given mode. 3210 :param decoder_name: What decoder to use. 3211 :param args: Additional parameters for the given decoder. For the 3212 default encoder ("raw"), it's recommended that you provide the 3213 full set of parameters:: 3214 3215 frombuffer(mode, size, data, "raw", mode, 0, 1) 3216 3217 :returns: An :py:class:`~PIL.Image.Image` object. 3218 3219 .. versionadded:: 1.1.4 3220 """ 3221 3222 _check_size(size) 3223 3224 # may pass tuple instead of argument list 3225 if len(args) == 1 and isinstance(args[0], tuple): 3226 args = args[0] 3227 3228 if decoder_name == "raw": 3229 if args == (): 3230 args = mode, 0, 1 3231 if args[0] in _MAPMODES: 3232 im = new(mode, (0, 0)) 3233 im = im._new(core.map_buffer(data, size, decoder_name, 0, args)) 3234 if mode == "P": 3235 from . import ImagePalette 3236 3237 im.palette = ImagePalette.ImagePalette("RGB", im.im.getpalette("RGB")) 3238 im.readonly = 1 3239 return im 3240 3241 return frombytes(mode, size, data, decoder_name, args)
Create an image from a buffer.
Arguments:
- mode: The mode of the image.
- size: The size of the image.
- data: The buffer data to create the image from.
- decoder_name: The name of the decoder to use. Default is 'raw'.
Returns:
A new Image object.
3254def fromarray(obj: SupportsArrayInterface, mode: str | None = None) -> Image: 3255 """ 3256 Creates an image memory from an object exporting the array interface 3257 (using the buffer protocol):: 3258 3259 from PIL import Image 3260 import numpy as np 3261 a = np.zeros((5, 5)) 3262 im = Image.fromarray(a) 3263 3264 If ``obj`` is not contiguous, then the ``tobytes`` method is called 3265 and :py:func:`~PIL.Image.frombuffer` is used. 3266 3267 In the case of NumPy, be aware that Pillow modes do not always correspond 3268 to NumPy dtypes. Pillow modes only offer 1-bit pixels, 8-bit pixels, 3269 32-bit signed integer pixels, and 32-bit floating point pixels. 3270 3271 Pillow images can also be converted to arrays:: 3272 3273 from PIL import Image 3274 import numpy as np 3275 im = Image.open("hopper.jpg") 3276 a = np.asarray(im) 3277 3278 When converting Pillow images to arrays however, only pixel values are 3279 transferred. This means that P and PA mode images will lose their palette. 3280 3281 :param obj: Object with array interface 3282 :param mode: Optional mode to use when reading ``obj``. Will be determined from 3283 type if ``None``. 3284 3285 This will not be used to convert the data after reading, but will be used to 3286 change how the data is read:: 3287 3288 from PIL import Image 3289 import numpy as np 3290 a = np.full((1, 1), 300) 3291 im = Image.fromarray(a, mode="L") 3292 im.getpixel((0, 0)) # 44 3293 im = Image.fromarray(a, mode="RGB") 3294 im.getpixel((0, 0)) # (44, 1, 0) 3295 3296 See: :ref:`concept-modes` for general information about modes. 3297 :returns: An image object. 3298 3299 .. versionadded:: 1.1.6 3300 """ 3301 arr = obj.__array_interface__ 3302 shape = arr["shape"] 3303 ndim = len(shape) 3304 strides = arr.get("strides", None) 3305 if mode is None: 3306 try: 3307 typekey = (1, 1) + shape[2:], arr["typestr"] 3308 except KeyError as e: 3309 msg = "Cannot handle this data type" 3310 raise TypeError(msg) from e 3311 try: 3312 mode, rawmode = _fromarray_typemap[typekey] 3313 except KeyError as e: 3314 typekey_shape, typestr = typekey 3315 msg = f"Cannot handle this data type: {typekey_shape}, {typestr}" 3316 raise TypeError(msg) from e 3317 else: 3318 rawmode = mode 3319 if mode in ["1", "L", "I", "P", "F"]: 3320 ndmax = 2 3321 elif mode == "RGB": 3322 ndmax = 3 3323 else: 3324 ndmax = 4 3325 if ndim > ndmax: 3326 msg = f"Too many dimensions: {ndim} > {ndmax}." 3327 raise ValueError(msg) 3328 3329 size = 1 if ndim == 1 else shape[1], shape[0] 3330 if strides is not None: 3331 if hasattr(obj, "tobytes"): 3332 obj = obj.tobytes() 3333 elif hasattr(obj, "tostring"): 3334 obj = obj.tostring() 3335 else: 3336 msg = "'strides' requires either tobytes() or tostring()" 3337 raise ValueError(msg) 3338 3339 return frombuffer(mode, size, obj, "raw", rawmode, 0, 1)
Create an image from a numpy array.
Arguments:
- obj: The numpy array to create the image from.
- mode: The mode of the image. If None, inferred from the array.
Returns:
A new Image object.
3779def effect_mandelbrot( 3780 size: tuple[int, int], extent: tuple[float, float, float, float], quality: int 3781) -> Image: 3782 """ 3783 Generate a Mandelbrot set covering the given extent. 3784 3785 :param size: The requested size in pixels, as a 2-tuple: 3786 (width, height). 3787 :param extent: The extent to cover, as a 4-tuple: 3788 (x0, y0, x1, y1). 3789 :param quality: Quality. 3790 """ 3791 return Image()._new(core.effect_mandelbrot(size, extent, quality))
Apply the Mandelbrot effect to the image.
Arguments:
- **kwargs: Additional arguments for the effect.
Returns:
The image with the Mandelbrot effect applied.
3794def effect_noise(size: tuple[int, int], sigma: float) -> Image: 3795 """ 3796 Generate Gaussian noise centered around 128. 3797 3798 :param size: The requested size in pixels, as a 2-tuple: 3799 (width, height). 3800 :param sigma: Standard deviation of noise. 3801 """ 3802 return Image()._new(core.effect_noise(size, sigma))
Apply noise to the image.
Arguments:
- **kwargs: Additional arguments for the effect.
Returns:
The image with noise applied.
3805def linear_gradient(mode: str) -> Image: 3806 """ 3807 Generate 256x256 linear gradient from black to white, top to bottom. 3808 3809 :param mode: Input mode. 3810 """ 3811 return Image()._new(core.linear_gradient(mode))
Create a linear gradient image.
Arguments:
- *args: Arguments for the gradient.
- **kwargs: Additional keyword arguments for the gradient.
Returns:
A new Image object with the linear gradient.
3814def radial_gradient(mode: str) -> Image: 3815 """ 3816 Generate 256x256 radial gradient from black to white, centre to edge. 3817 3818 :param mode: Input mode. 3819 """ 3820 return Image()._new(core.radial_gradient(mode))
Create a radial gradient image.
Arguments:
- *args: Arguments for the gradient.
- **kwargs: Additional keyword arguments for the gradient.
Returns:
A new Image object with the radial gradient.
3642def register_open( 3643 id: str, 3644 factory: ( 3645 Callable[[IO[bytes], str | bytes], ImageFile.ImageFile] 3646 | type[ImageFile.ImageFile] 3647 ), 3648 accept: Callable[[bytes], bool | str] | None = None, 3649) -> None: 3650 """ 3651 Register an image file plugin. This function should not be used 3652 in application code. 3653 3654 :param id: An image format identifier. 3655 :param factory: An image file factory method. 3656 :param accept: An optional function that can be used to quickly 3657 reject images having another format. 3658 """ 3659 id = id.upper() 3660 if id not in ID: 3661 ID.append(id) 3662 OPEN[id] = factory, accept
Register a new image format.
Arguments:
- format: The name of the format.
- factory: The factory function to create the image.
- accept: A function to check if the format is accepted.
Returns:
None
3665def register_mime(id: str, mimetype: str) -> None: 3666 """ 3667 Registers an image MIME type by populating ``Image.MIME``. This function 3668 should not be used in application code. 3669 3670 ``Image.MIME`` provides a mapping from image format identifiers to mime 3671 formats, but :py:meth:`~PIL.ImageFile.ImageFile.get_format_mimetype` can 3672 provide a different result for specific images. 3673 3674 :param id: An image format identifier. 3675 :param mimetype: The image MIME type for this format. 3676 """ 3677 MIME[id.upper()] = mimetype
Register a new MIME type for the image format.
Arguments:
- format: The name of the format.
- mime: The MIME type to register.
Returns:
None
3680def register_save( 3681 id: str, driver: Callable[[Image, IO[bytes], str | bytes], None] 3682) -> None: 3683 """ 3684 Registers an image save function. This function should not be 3685 used in application code. 3686 3687 :param id: An image format identifier. 3688 :param driver: A function to save images in this format. 3689 """ 3690 SAVE[id.upper()] = driver
Register a new save format for the image.
Arguments:
- format: The name of the format.
- factory: The factory function to create the image.
Returns:
None
3693def register_save_all( 3694 id: str, driver: Callable[[Image, IO[bytes], str | bytes], None] 3695) -> None: 3696 """ 3697 Registers an image function to save all the frames 3698 of a multiframe format. This function should not be 3699 used in application code. 3700 3701 :param id: An image format identifier. 3702 :param driver: A function to save images in this format. 3703 """ 3704 SAVE_ALL[id.upper()] = driver
Register a new save_all format for the image.
Arguments:
- format: The name of the format.
- factory: The factory function to create the image.
Returns:
None
3707def register_extension(id: str, extension: str) -> None: 3708 """ 3709 Registers an image extension. This function should not be 3710 used in application code. 3711 3712 :param id: An image format identifier. 3713 :param extension: An extension used for this format. 3714 """ 3715 EXTENSION[extension.lower()] = id.upper()
Registers an image extension. This function should not be used in application code.
Parameters
- id: An image format identifier.
- extension: An extension used for this format.
3718def register_extensions(id: str, extensions: list[str]) -> None: 3719 """ 3720 Registers image extensions. This function should not be 3721 used in application code. 3722 3723 :param id: An image format identifier. 3724 :param extensions: A list of extensions used for this format. 3725 """ 3726 for extension in extensions: 3727 register_extension(id, extension)
Register new file extensions for the image format.
Arguments:
- format: The name of the format.
- extensions: A list of file extensions to register.
Returns:
None
3730def registered_extensions() -> dict[str, str]: 3731 """ 3732 Returns a dictionary containing all file extensions belonging 3733 to registered plugins 3734 """ 3735 init() 3736 return EXTENSION
Get the registered file extensions for the image format.
Arguments:
- format: The name of the format.
Returns:
A list of registered file extensions.
3739def register_decoder(name: str, decoder: type[ImageFile.PyDecoder]) -> None: 3740 """ 3741 Registers an image decoder. This function should not be 3742 used in application code. 3743 3744 :param name: The name of the decoder 3745 :param decoder: An ImageFile.PyDecoder object 3746 3747 .. versionadded:: 4.1.0 3748 """ 3749 DECODERS[name] = decoder
Register a new decoder for the image format.
Arguments:
- format: The name of the format.
- decoder: The decoder function to use.
Returns:
None
3752def register_encoder(name: str, encoder: type[ImageFile.PyEncoder]) -> None: 3753 """ 3754 Registers an image encoder. This function should not be 3755 used in application code. 3756 3757 :param name: The name of the encoder 3758 :param encoder: An ImageFile.PyEncoder object 3759 3760 .. versionadded:: 4.1.0 3761 """ 3762 ENCODERS[name] = encoder
Register a new encoder for the image format.
Arguments:
- format: The name of the format.
- encoder: The encoder function to use.
Returns:
None