from moviepy.editor import VideoFileClip, TextClip, CompositeVideoClip, ImageClip

from PIL import Image, ImageDraw
import numpy as np
import textwrap

def create_rounded_rectangle(size, color, radius):
"""Creates a rounded rectangle as a NumPy array."""
width, height = size
img = Image.new("RGBA", (width, height), (0, 0, 0, 0))
draw = ImageDraw.Draw(img)
draw.rounded_rectangle(
[(0, 0), (width, height)],
radius=radius,
fill=color,
)
return np.array(img)

def wrap_text(text, font_size, max_width, font_path):
"""Wrap text to fit within max_width."""
text_clip = TextClip(text, fontsize=font_size, color="white", font=font_path)
line_width = text_clip.w
char_count = len(text)
avg_char_width = line_width / char_count
max_chars_per_line = int(max_width / avg_char_width)
wrapped_text = "\n".join(textwrap.wrap(text, width=max_chars_per_line))
return wrapped_text

# Load the video
video_path = "/Users/jitendersingh/Downloads/background.mp4"
video = VideoFileClip(video_path)

# Text and parameters
text = "Your Text Here Your Text Here Your Text Here Your Text Here Your Text Here Your Text Here Your Text Here"
font_path = "/System/Library/Fonts/Supplemental/Arial Bold.ttf" # Update font if needed
font_size = 80
margin = 100 # Margin for width
max_text_width = video.w - 2 * margin # Maximum width available for the text

# Wrap the text to fit within the frame, only applying margin on width
wrapped_text = wrap_text(text, font_size, max_text_width, font_path)

# Create the text clip with the wrapped text
text_clip = TextClip(wrapped_text, fontsize=font_size, color='white', font=font_path, align='center').set_duration(video.duration)

# Create a rounded rectangle background for the text (apply margin only in width)
bg_size = (text_clip.w + 20, text_clip.h + 20) # Add 20px padding for background
bg_color = (0, 0, 255, 255) # Blue background
rounded_rect = create_rounded_rectangle(bg_size, bg_color, radius=15)
background_clip = ImageClip(rounded_rect).set_duration(video.duration)

# Combine text and background
text_with_bg = CompositeVideoClip([
background_clip.set_position('center'),
text_clip.set_position('center')
]).set_duration(video.duration)

# Add animation: move from top center to 200px below the top
def animated_position(t):
final_y = 20 # Final Y position
initial_y = -text_with_bg.h # Start off-screen
return ('center', initial_y + (final_y - initial_y) * min(t / 0.5, 1)) # 0.5 seconds for animation

animated_text = text_with_bg.set_position(animated_position)

# Overlay the animated text on the video
final_video = CompositeVideoClip([video, animated_text])

# Export the final video
output_path = "/Users/jitendersingh/Downloads/output_video.mp4"
final_video.write_videofile(output_path, codec='libx264', fps=video.fps)

0 comments:

Post a Comment

 
Top