0
# Core Image Operations
1
2
Essential image manipulation functions that form the foundation of Pillow's image processing capabilities. These operations handle the fundamental tasks of opening, creating, transforming, and saving images across multiple formats.
3
4
## Capabilities
5
6
### Image Creation and Loading
7
8
Create new images or load existing images from files, bytes, or other data sources.
9
10
```python { .api }
11
def new(mode, size, color=0):
12
"""
13
Creates a new image with the given mode and size.
14
15
Parameters:
16
- mode (str): The mode to use for the new image (e.g., "RGB", "RGBA", "L")
17
- size (tuple): Size tuple (width, height)
18
- color (int | tuple | str): Color to use for the image. Default is 0 (black)
19
20
Returns:
21
Image: A new Image object
22
"""
23
24
def open(fp, mode="r", formats=None):
25
"""
26
Opens and identifies an image file.
27
28
Parameters:
29
- fp (str | Path | file): Filename, pathlib.Path object, or file object
30
- mode (str): Mode for opening the file ("r" for reading)
31
- formats (list): List of format names to attempt
32
33
Returns:
34
Image: An Image object
35
36
Raises:
37
UnidentifiedImageError: If the image cannot be opened
38
IOError: If the file cannot be found or opened
39
"""
40
41
def frombytes(mode, size, data, decoder_name="raw", *args):
42
"""
43
Creates an image from bytes data.
44
45
Parameters:
46
- mode (str): The image mode
47
- size (tuple): Size tuple (width, height)
48
- data (bytes): Raw image data
49
- decoder_name (str): Decoder to use
50
51
Returns:
52
Image: A new Image object
53
"""
54
55
def fromarray(obj, mode=None):
56
"""
57
Creates an image from an array-like object.
58
59
Parameters:
60
- obj: Array-like object (numpy array, etc.)
61
- mode (str): Image mode to use
62
63
Returns:
64
Image: A new Image object
65
"""
66
```
67
68
### Image Properties and Information
69
70
Access image metadata and properties.
71
72
```python { .api }
73
class Image:
74
@property
75
def size(self) -> tuple[int, int]:
76
"""Image size as (width, height) tuple."""
77
78
@property
79
def width(self) -> int:
80
"""Image width in pixels."""
81
82
@property
83
def height(self) -> int:
84
"""Image height in pixels."""
85
86
@property
87
def mode(self) -> str:
88
"""Image mode (e.g., "RGB", "RGBA", "L")."""
89
90
@property
91
def format(self) -> str | None:
92
"""Original format of the image file."""
93
94
@property
95
def info(self) -> dict:
96
"""Dictionary containing image metadata."""
97
98
def getbands(self) -> tuple[str, ...]:
99
"""
100
Returns the names of the bands in the image.
101
102
Returns:
103
tuple: Band names
104
"""
105
106
def getbbox(self) -> tuple[int, int, int, int] | None:
107
"""
108
Calculates the bounding box of non-zero regions.
109
110
Returns:
111
tuple | None: Bounding box as (left, top, right, bottom) or None
112
"""
113
114
def getextrema(self) -> tuple | tuple[tuple, ...]:
115
"""
116
Gets the minimum and maximum pixel values.
117
118
Returns:
119
tuple: Min/max values for each band
120
"""
121
```
122
123
### Geometric Transformations
124
125
Transform images through resizing, rotation, cropping, and other geometric operations.
126
127
```python { .api }
128
class Image:
129
def resize(self, size, resample=None, box=None, reducing_gap=None):
130
"""
131
Returns a resized copy of this image.
132
133
Parameters:
134
- size (tuple): Target size as (width, height)
135
- resample (int): Resampling filter (Resampling.NEAREST, .BILINEAR, .BICUBIC, .LANCZOS)
136
- box (tuple): Region to resize from as (left, top, right, bottom)
137
- reducing_gap (float): Optimization for downscaling
138
139
Returns:
140
Image: Resized image
141
"""
142
143
def rotate(self, angle, resample=0, expand=0, center=None, translate=None, fillcolor=None):
144
"""
145
Returns a rotated copy of this image.
146
147
Parameters:
148
- angle (float): Rotation angle in degrees (counter-clockwise)
149
- resample (int): Resampling filter
150
- expand (bool): If True, expands output to fit entire rotated image
151
- center (tuple): Center of rotation as (x, y)
152
- translate (tuple): Post-rotation translation as (x, y)
153
- fillcolor (int | tuple | str): Color for areas outside original image
154
155
Returns:
156
Image: Rotated image
157
"""
158
159
def crop(self, box=None):
160
"""
161
Returns a rectangular region from this image.
162
163
Parameters:
164
- box (tuple): Crop rectangle as (left, top, right, bottom)
165
166
Returns:
167
Image: Cropped image
168
"""
169
170
def thumbnail(self, size, resample=3, reducing_gap=2.0):
171
"""
172
Make this image into a thumbnail (modifies image in place).
173
174
Parameters:
175
- size (tuple): Maximum size as (width, height)
176
- resample (int): Resampling filter
177
- reducing_gap (float): Optimization for downscaling
178
"""
179
180
def transpose(self, method):
181
"""
182
Transpose image (flip or rotate in 90-degree steps).
183
184
Parameters:
185
- method (int): Transpose method (Transpose.FLIP_LEFT_RIGHT, etc.)
186
187
Returns:
188
Image: Transposed image
189
"""
190
```
191
192
### Color and Mode Operations
193
194
Convert between color modes and manipulate color properties.
195
196
```python { .api }
197
class Image:
198
def convert(self, mode=None, matrix=None, dither=None, palette=0, colors=256):
199
"""
200
Returns a converted copy of this image.
201
202
Parameters:
203
- mode (str): Target mode ("L", "RGB", "RGBA", "CMYK", etc.)
204
- matrix (sequence): Conversion matrix for "RGB" to "L" conversion
205
- dither (int): Dithering method (Dither.NONE, .ORDERED, .FLOYDSTEINBERG)
206
- palette (int): Palette mode (Palette.WEB, .ADAPTIVE)
207
- colors (int): Number of colors for palette conversion
208
209
Returns:
210
Image: Converted image
211
"""
212
213
def quantize(self, colors=256, method=None, kmeans=0, palette=None, dither=1):
214
"""
215
Convert image to 'P' mode with specified number of colors.
216
217
Parameters:
218
- colors (int): Number of colors in result (2-256)
219
- method (int): Quantization method (Quantize.MEDIANCUT, etc.)
220
- kmeans (int): K-means iteration count
221
- palette (Image): Palette image to use
222
- dither (int): Dithering method
223
224
Returns:
225
Image: Quantized image
226
"""
227
228
def split(self):
229
"""
230
Split image into individual bands.
231
232
Returns:
233
tuple: Tuple of single-band images
234
"""
235
236
def getchannel(self, channel):
237
"""
238
Returns an image containing a single channel.
239
240
Parameters:
241
- channel (int | str): Band index or name
242
243
Returns:
244
Image: Single-channel image
245
"""
246
```
247
248
### Image I/O Operations
249
250
Save images to files or get image data as bytes.
251
252
```python { .api }
253
class Image:
254
def save(self, fp, format=None, **params):
255
"""
256
Saves this image under the given filename.
257
258
Parameters:
259
- fp (str | Path | file): Target filename, pathlib.Path, or file object
260
- format (str): Image format ("JPEG", "PNG", "TIFF", etc.)
261
- **params: Format-specific parameters
262
263
Raises:
264
ValueError: If format cannot be determined
265
IOError: If the file cannot be written
266
"""
267
268
def tobytes(self, encoder_name="raw", *args):
269
"""
270
Return image as bytes.
271
272
Parameters:
273
- encoder_name (str): Encoder to use
274
- *args: Encoder arguments
275
276
Returns:
277
bytes: Image data
278
"""
279
280
def tobitmap(self, name="image"):
281
"""
282
Returns the image converted to an X11 bitmap.
283
284
Parameters:
285
- name (str): Name to use in bitmap
286
287
Returns:
288
bytes: X11 bitmap data
289
"""
290
```
291
292
### Multi-frame Image Support
293
294
Handle animated images and image sequences.
295
296
```python { .api }
297
class Image:
298
@property
299
def is_animated(self) -> bool:
300
"""True if image has multiple frames."""
301
302
@property
303
def n_frames(self) -> int:
304
"""Number of frames in image."""
305
306
def seek(self, frame):
307
"""
308
Seeks to a specific frame in a multi-frame image.
309
310
Parameters:
311
- frame (int): Frame number to seek to
312
"""
313
314
def tell(self) -> int:
315
"""
316
Returns the current frame number.
317
318
Returns:
319
int: Current frame number
320
"""
321
```
322
323
### Pixel Access and Manipulation
324
325
Direct pixel-level access and manipulation.
326
327
```python { .api }
328
class Image:
329
def getpixel(self, xy):
330
"""
331
Returns the pixel value at a given position.
332
333
Parameters:
334
- xy (tuple): Coordinate tuple (x, y)
335
336
Returns:
337
int | tuple: Pixel value
338
"""
339
340
def putpixel(self, xy, value):
341
"""
342
Modifies the pixel at a given position.
343
344
Parameters:
345
- xy (tuple): Coordinate tuple (x, y)
346
- value (int | tuple): New pixel value
347
"""
348
349
def point(self, lut, mode=None):
350
"""
351
Maps image through lookup table or function.
352
353
Parameters:
354
- lut (sequence | function): Lookup table or mapping function
355
- mode (str): Output image mode
356
357
Returns:
358
Image: Mapped image
359
"""
360
361
def paste(self, im, box=None, mask=None):
362
"""
363
Pastes another image into this image.
364
365
Parameters:
366
- im (Image | int | tuple | str): Source image or color
367
- box (tuple): Target region as (left, top) or (left, top, right, bottom)
368
- mask (Image): Optional mask image
369
"""
370
```
371
372
### Utility Functions
373
374
Helper functions for image processing.
375
376
```python { .api }
377
def merge(mode, bands):
378
"""
379
Merge a set of single-band images into a multi-band image.
380
381
Parameters:
382
- mode (str): Mode of output image
383
- bands (sequence): Sequence of single-band images
384
385
Returns:
386
Image: Multi-band image
387
"""
388
389
def blend(im1, im2, alpha):
390
"""
391
Creates a new image by interpolating between two input images.
392
393
Parameters:
394
- im1 (Image): First image
395
- im2 (Image): Second image
396
- alpha (float): Interpolation factor (0.0 to 1.0)
397
398
Returns:
399
Image: Blended image
400
"""
401
402
def composite(image1, image2, mask):
403
"""
404
Create composite image using transparency mask.
405
406
Parameters:
407
- image1 (Image): First image
408
- image2 (Image): Second image
409
- mask (Image): Mask image
410
411
Returns:
412
Image: Composite image
413
"""
414
415
def alpha_composite(im1, im2):
416
"""
417
Alpha composite two RGBA images.
418
419
Parameters:
420
- im1 (Image): First RGBA image
421
- im2 (Image): Second RGBA image
422
423
Returns:
424
Image: Composite RGBA image
425
"""
426
```
427
428
## Usage Examples
429
430
### Basic Image Processing Pipeline
431
432
```python
433
from PIL import Image
434
435
# Open and process an image
436
with Image.open("input.jpg") as img:
437
# Get image info
438
print(f"Original size: {img.size}, mode: {img.mode}")
439
440
# Convert to RGB if needed
441
if img.mode != "RGB":
442
img = img.convert("RGB")
443
444
# Resize maintaining aspect ratio
445
img.thumbnail((800, 600), Image.Resampling.LANCZOS)
446
447
# Rotate the image
448
rotated = img.rotate(45, expand=True, fillcolor="white")
449
450
# Save with quality setting
451
rotated.save("output.jpg", "JPEG", quality=85, optimize=True)
452
```
453
454
### Working with Image Channels
455
456
```python
457
from PIL import Image
458
459
# Load an RGB image
460
img = Image.open("color_image.jpg")
461
462
# Split into individual channels
463
r, g, b = img.split()
464
465
# Process individual channels
466
enhanced_red = r.point(lambda x: x * 1.2) # Brighten red channel
467
468
# Merge channels back
469
enhanced = Image.merge("RGB", [enhanced_red, g, b])
470
471
# Or get a single channel
472
red_only = img.getchannel("R")
473
red_only.save("red_channel.jpg")
474
```
475
476
### Creating Images from Data
477
478
```python
479
from PIL import Image
480
import numpy as np
481
482
# Create from numpy array
483
data = np.random.rand(100, 100, 3) * 255
484
img = Image.fromarray(data.astype('uint8'), 'RGB')
485
486
# Create new blank image
487
blank = Image.new("RGBA", (400, 300), (255, 255, 255, 128))
488
489
# Create gradient
490
width, height = 256, 256
491
gradient = Image.new("L", (width, height))
492
for x in range(width):
493
for y in range(height):
494
gradient.putpixel((x, y), x)
495
```