[파이썬] Pillow 이미지에 텍스트 추가하기

Pillow

Pillow is a popular Python library for image processing tasks. It provides a wide range of functionalities, including adding text to images. Adding text to an image can be useful in various applications, such as creating watermarks, adding captions, or generating meme images.

In this tutorial, we will explore how to use Pillow to add text to an image in Python. Let’s get started!

Installing Pillow

Before we can begin, we need to install Pillow. Open a terminal or command prompt and enter the following command:

pip install Pillow

Once the installation is complete, we can start working with Pillow in our Python script.

Loading and Displaying the Image

First, we need to load the image onto which we want to add the text. We can use the Image.open() method to open the image file. Make sure to specify the correct image file path.

from PIL import Image

# Load the image
image = Image.open('image.jpg')

# Display the image
image.show()

Adding Text to the Image

To add text to the image, we will use the ImageDraw.Draw() method. We need to create an instance of the ImageDraw class and pass the image as an argument. Then, we can use the text() method of the ImageDraw class to add the desired text.

from PIL import Image, ImageDraw, ImageFont

# Load the image
image = Image.open('image.jpg')

# Create an instance of ImageDraw
draw = ImageDraw.Draw(image)

# Specify the font file path
font = ImageFont.truetype('arial.ttf', size=30)

# Specify the text, position, and color
text = "Hello, Pillow!"
position = (50, 50)
color = (255, 255, 255)  # white

# Add text to the image
draw.text(position, text, font=font, fill=color)

# Display the modified image
image.show()

Saving the Modified Image

Once we have added the text to the image, we can save the modified image using the save() method. Specify the desired file path and the desired image format.

# Save the modified image
image.save('modified_image.jpg')

That’s it! We have successfully added text to an image using Pillow in Python. We can further tweak the font, position, color, and other parameters to achieve the desired effect.

Pillow provides many more advanced features for image processing and manipulation. You can explore the official Pillow documentation for more information on the library’s capabilities and usage.

I hope you found this tutorial helpful! Happy coding!