[파이썬] Pillow 그림자 효과 추가하기

Pillow

In this blog post, we will explore how to add a shadow effect to an image using the Pillow library in Python. Shadows can add depth and dimension to images, making them visually appealing.

Installing Pillow

Before we start, we need to install the Pillow library. Open your command prompt or terminal and run the following command:

pip install Pillow

Once the installation is complete, we can proceed with adding the shadow effect.

Adding the Shadow Effect

Step 1: Importing the necessary libraries

First, we need to import the necessary libraries PIL and ImageFilter. The PIL library provides the core functionality for working with images, and ImageFilter allows us to apply various filters to the images, including the shadow effect.

from PIL import Image, ImageFilter

Step 2: Loading the image

Next, we need to load the image that we want to apply the shadow effect to. You can use your own image by providing the path to the image file, or you can use a sample image for testing.

image_path = "path/to/your/image.jpg"
image = Image.open(image_path)

Step 3: Applying the shadow effect

To apply the shadow effect, we will use the ImageFilter.GaussianBlur function from the ImageFilter library. We will create a blurred version of the original image, and then paste it onto a new blank image with a slight offset to create the shadow effect.

shadow_radius = 20  # adjust the radius for stronger or weaker shadow effect

# Create a blurred version of the image
blurred_image = image.filter(ImageFilter.GaussianBlur(shadow_radius))

# Create a new blank image with the same size as the original image
shadow_image = Image.new("RGB", image.size)

# Paste the blurred image onto the shadow image with a slight offset
shadow_image.paste(blurred_image, (5, 5))

# Composite the original image and the shadow image
final_image = Image.alpha_composite(image.convert("RGBA"), shadow_image.convert("RGBA"))

# Save the final image
final_image.save("path/to/save/final_image.jpg")

Step 4: Viewing the result

You can view the result by opening the saved final image. The image will have a shadow effect applied to it, which adds depth and dimension.

Conclusion

In this blog post, we learned how to add a shadow effect to an image using the Pillow library in Python. Shadows can enhance the visual appeal of images and make them more engaging. Experiment with different shadow radius values and image placements to achieve the desired effect. Have fun exploring and incorporating shadow effects into your images!