# Import the modules
import cv2 # For image processing
import numpy as np # For array manipulation
import textwrap # For wrapping text
# Define the function to create a featured image
def create_featured_image(image_path, text, font, font_size, font_color, bg_color):
# Load the image and get its dimensions
image = cv2.imread(image_path)
height, width, _ = image.shape
# Create a margin for the text section
margin = 20
# Calculate the height of the text section based on the font size and number of lines
lines = textwrap.wrap(text, width=40) # Wrap the text into 40 characters per line
num_lines = len(lines) # Get the number of lines
line_height = font_size + margin # Get the height of each line
text_height = num_lines * line_height + margin # Get the total height of the text section
# Create a blank image for the text section with the same width as the original image and the calculated height
text_image = np.zeros((text_height, width, 3), dtype=np.uint8)
text_image[:] = bg_color # Fill the image with the background color
# Draw the text on the text image using cv2.putText
y = margin + font_size # The initial y coordinate for the text
for line in lines: # Loop through each line of text
cv2.putText(text_image, line, (margin, y), font, font_size / 32, font_color, 1) # Put the text on the image
y += line_height # Increment the y coordinate for the next line
# Concatenate the original image and the text image vertically using np.vstack
featured_image = np.vstack((image, text_image))
# Return the featured image
return featured_image
# Test the function with an example image and text
image_path = "example.jpg" # The path to the image file
text = "How to create a featured image with Python" # The text to be added
font = cv2.FONT_HERSHEY_SIMPLEX # The font to be used
font_size = 32 # The font size in pixels
font_color = (255, 255, 255) # The font color in BGR format (white)
bg_color = (0, 0, 0) # The background color in BGR format (black)
# Call the function and save the result as a new image file
result = create_featured_image(image_path, text, font, font_size, font_color, bg_color)
cv2.imwrite("result.jpg", result)
Comments