|
| 1 | +--- |
| 2 | +Title: '.blend()' |
| 3 | +Description: 'Creates a new image by interpolating between two input images using a constant alpha value.' |
| 4 | +Subjects: |
| 5 | + - 'Computer Science' |
| 6 | + - 'Data Science' |
| 7 | +Tags: |
| 8 | + - 'Images' |
| 9 | + - 'Pillow' |
| 10 | + - 'Python' |
| 11 | +CatalogContent: |
| 12 | + - 'learn-python-3' |
| 13 | + - 'paths/data-science' |
| 14 | +--- |
| 15 | + |
| 16 | +The **`.blend()`** method in Pillow's Image module creates a new image by interpolating between two input images using a constant alpha value. This method is a powerful tool for image processing that allows to combine or mix two images with different levels of transparency. |
| 17 | + |
| 18 | +Image blending is commonly used in graphics, image processing, and computer vision to achieve various visual effects like smooth transitions, overlays, watermarks, and creating composite images. The blend operation performs a pixel-by-pixel calculation using a weighted sum controlled by the alpha parameter. |
| 19 | + |
| 20 | +## Syntax |
| 21 | + |
| 22 | +```pseudo |
| 23 | +PIL.Image.blend(im1, im2, alpha) |
| 24 | +``` |
| 25 | + |
| 26 | +**Parameters:** |
| 27 | + |
| 28 | +- `im1`: The first image. |
| 29 | +- `im2`: The second image. Must have the same mode and size as the first image. |
| 30 | +- `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. |
| 31 | + |
| 32 | +**Return value:** |
| 33 | + |
| 34 | +This method returns an `Image` object containing the blended result. |
| 35 | + |
| 36 | +## Example 1: Basic Image Blending with Pillow |
| 37 | + |
| 38 | +This example demonstrates how to use the `.blend()` method to create a simple 50/50 blend of two images. |
| 39 | + |
| 40 | +```py |
| 41 | +from PIL import Image |
| 42 | + |
| 43 | +# Load two images |
| 44 | +image1 = Image.open("mountains.jpg") |
| 45 | +image2 = Image.open("ocean.jpg") |
| 46 | + |
| 47 | +# Make sure both images have the same mode and size |
| 48 | +image2 = image2.resize(image1.size) |
| 49 | +image2 = image2.convert(image1.mode) |
| 50 | + |
| 51 | +# Blend the images with alpha = 0.5 (equal parts of both images) |
| 52 | +blended_image = Image.blend(image1, image2, alpha=0.5) |
| 53 | + |
| 54 | +# Save the result |
| 55 | +blended_image.save("blended_image.png") |
| 56 | +``` |
| 57 | + |
| 58 | + |
| 59 | + |
| 60 | +This basic example loads two images, ensures they have the same size and mode (required by the `.blend()` method), and creates a new image that contains 50% of each input image. The alpha value of 0.5 gives equal weight to both images in the final result. |
| 61 | + |
| 62 | +## Example 2: Creating a Fade Effect Between Images |
| 63 | + |
| 64 | +This example shows how to create a series of images that fade from one image to another, which could be used to create transition animations. |
| 65 | + |
| 66 | +```py |
| 67 | +from PIL import Image |
| 68 | +import os |
| 69 | + |
| 70 | +# Load two images |
| 71 | +image1 = Image.open("mountains.jpg").convert("RGBA") |
| 72 | +image2 = Image.open("ocean.jpg").convert("RGBA") |
| 73 | + |
| 74 | +# Resize the second image to match the first |
| 75 | +image2 = image2.resize(image1.size) |
| 76 | + |
| 77 | +# Create a directory for the frames if it doesn't exist |
| 78 | +os.makedirs("frames", exist_ok=True) |
| 79 | + |
| 80 | +# Create 10 frames with different alpha values |
| 81 | +frames = 10 |
| 82 | +for i in range(frames + 1): |
| 83 | + # Calculate alpha for this frame |
| 84 | + alpha = i / frames |
| 85 | + |
| 86 | + # Blend the images with the current alpha |
| 87 | + blended = Image.blend(image1, image2, alpha) |
| 88 | + |
| 89 | + # Save the frame |
| 90 | + blended.save(f"frames/frame_{i:02d}.png") |
| 91 | + |
| 92 | + # Print progress |
| 93 | + print(f"Created frame {i}/{frames} with alpha = {alpha:.2f}") |
| 94 | + |
| 95 | +print("All frames created successfully!") |
| 96 | +``` |
| 97 | + |
| 98 | +This example creates a series of images that gradually transition from the first image to the second by incrementally increasing the alpha value. This technique is useful for creating smooth transitions between images for animations, slideshows, or video effects. |
| 99 | + |
| 100 | +## Example 3: Creating a Watermark Effect with Variable Opacity |
| 101 | + |
| 102 | +This example demonstrates how to use the `.blend()` method to apply a watermark to an image with adjustable opacity. |
| 103 | + |
| 104 | +```py |
| 105 | +from PIL import Image, ImageDraw, ImageFont |
| 106 | + |
| 107 | +def create_watermark(text, size, font_size=60, color=(255, 255, 255, 128)): |
| 108 | + """Create a transparent image with text as a watermark.""" |
| 109 | + watermark = Image.new('RGBA', size, (0, 0, 0, 0)) |
| 110 | + draw = ImageDraw.Draw(watermark) |
| 111 | + |
| 112 | + # Load font |
| 113 | + try: |
| 114 | + font = ImageFont.truetype("arial.ttf", font_size) |
| 115 | + except IOError: |
| 116 | + font = ImageFont.load_default() |
| 117 | + |
| 118 | + # Get text dimensions |
| 119 | + text_bbox = draw.textbbox((0, 0), text, font=font) |
| 120 | + text_width, text_height = text_bbox[2] - text_bbox[0], text_bbox[3] - text_bbox[1] |
| 121 | + |
| 122 | + # Center text position |
| 123 | + position = ((size[0] - text_width) // 2, (size[1] - text_height) // 2) |
| 124 | + |
| 125 | + # Draw the text |
| 126 | + draw.text(position, text, font=font, fill=color) |
| 127 | + |
| 128 | + return watermark |
| 129 | + |
| 130 | +# Load base image |
| 131 | +base_image = Image.open("mountains.jpg").convert("RGBA") |
| 132 | + |
| 133 | +# Create a transparent watermark |
| 134 | +watermark = create_watermark("Copyright 2025", base_image.size) |
| 135 | + |
| 136 | +# Create a solid transparent image for blending |
| 137 | +transparent_layer = Image.new("RGBA", base_image.size, (255, 255, 255, 0)) |
| 138 | + |
| 139 | +# Blend watermark onto the transparent layer |
| 140 | +blended_watermark = Image.blend(transparent_layer, watermark, alpha=1.0) |
| 141 | + |
| 142 | +# Blend the base image with the blended watermark |
| 143 | +result = Image.blend(base_image, blended_watermark, alpha=0.3) # Adjust alpha as needed |
| 144 | + |
| 145 | +# Save and display |
| 146 | +result.save("watermarked_image.png") |
| 147 | +result.show() |
| 148 | +``` |
| 149 | + |
| 150 | + |
| 151 | + |
| 152 | +This example creates a watermark text overlay on an image. By adjusting the alpha value in the `.blend()` the opacity of the watermark can be controlled. This technique is useful for adding copyright information, branding, or other textual overlays to images while maintaining control over their visibility. |
0 commit comments