How to add text to image in Django

To add text to an image in Django, you can use the Python Imaging Library (Pillow).

1. Install Pillow

First, you’ll need to install Pillow if you haven’t already. You can install it using pip:

pip install pillow

2. Create a Django View to Add Text to an Image

Create a Django view that will open an image, add text to it, and then return the modified image.

from django.http import HttpResponse
from PIL import Image, ImageDraw, ImageFont
import io

def add_text_to_image(request):
    # Open an existing image
    image = Image.open("imagepath.jpg")

    # Initialize ImageDraw
    draw = ImageDraw.Draw(image)

    # Define the text to add and its position
    text = "Hello, Django!"
    position = (50, 50)

    # Define font and size (Pillow requires a .ttf file for custom fonts)
    font = ImageFont.truetype("fontpath.ttf", 40)

    # Define the text color
    color = "rgb(255, 255, 255)"  # white

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

    # Save the image to a BytesIO object
    image_io = io.BytesIO()
    image.save(image_io, format="JPEG")
    image_io.seek(0)

    # Return the image as a response
    return HttpResponse(image_io, content_type="image/jpeg")

3. Create a URL Pattern

You need to map the view to a URL in your urls.py file:

from django.urls import path
from .views import add_text_to_image

urlpatterns = [
    path('add-text/', add_text_to_image, name='add_text_to_image'),
]

4. Access the URL

You can now access this URL in your browser (e.g., http://localhost:8000/add-text/), and it will display the image with the added text.

5. Optional: Use an Uploaded Image

If you want to add text to an image uploaded by a user, you can modify the view to handle file uploads:

from django.shortcuts import render
from django.http import HttpResponse
from PIL import Image, ImageDraw, ImageFont
import io

def add_text_to_image(request):
    if request.method == 'POST' and request.FILES['image']:
        # Open the uploaded image
        image = Image.open(request.FILES['image'])

        # Initialize ImageDraw
        draw = ImageDraw.Draw(image)

        # Define the text to add and its position
        text = request.POST.get('text', 'Hello, Django!')
        position = (50, 50)

        # Define font and size
        font = ImageFont.truetype("path/to/your/font.ttf", 40)

        # Define the text color
        color = "rgb(255, 255, 255)"  # white

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

        # Save the image to a BytesIO object
        image_io = io.BytesIO()
        image.save(image_io, format="JPEG")
        image_io.seek(0)

        # Return the image as a response
        return HttpResponse(image_io, content_type="image/jpeg")

    return render(request, 'upload_image.html')

6. Create a Simple HTML Form for Upload

Create an upload_image.html template:

<form method="POST" enctype="multipart/form-data">
    {% csrf_token %}
    <input type="file" name="image" accept="image/*" required>
    <input type="text" name="text" placeholder="Enter text" required>
    <button type="submit">Upload and Add Text</button>
</form>

Now, you can upload an image through this form, and the server will process the image, add the text, and return it to you.