How to Make an Image Transparent with Python, Dockerize It, and Run It on Kubernetes

Introduction

In this article, we will walk through the process of making an image transparent using Python, containerizing the application with Docker, and deploying it to an HTTP server running on Kubernetes. This end-to-end guide will help you understand the basics of image processing, containerization, and orchestration.

Step 1: Making an Image Transparent with Python

First, let’s write a Python script that converts an image’s white background to transparent. We’ll use the Pillow library for image manipulation.

  1. Install Pillow:bashCopy codepip install pillow
  2. Create the Python Script:pythonCopy codefrom PIL import Image def make_image_transparent(image_path, output_path): image = Image.open(image_path).convert("RGBA") datas = image.getdata() new_data = [] for item in datas: if item[0] > 200 and item[1] > 200 and item[2] > 200: new_data.append((255, 255, 255, 0)) else: new_data.append(item) image.putdata(new_data) image.save(output_path) if __name__ == "__main__": input_image_path = "input_image.png" output_image_path = "output_image.png" make_image_transparent(input_image_path, output_image_path)

Save this script as make_transparent.py.

Step 2: Dockerize the Python Application

To run this Python script in a container, we need to create a Dockerfile.

  1. Create a Dockerfile:DockerfileCopy code# Use an official Python runtime as a parent image FROM python:3.9-slim # Set the working directory WORKDIR /app # Copy the current directory contents into the container COPY . /app # Install any needed packages specified in requirements.txt RUN pip install --no-cache-dir pillow # Make port 80 available to the world outside this container EXPOSE 80 # Define environment variable ENV NAME World # Run make_image_transparent.py when the container launches CMD ["python", "make_transparent.py"]
  2. Build the Docker Image:bashCopy codedocker build -t image-transparency .
  3. Run the Docker Container:bashCopy codedocker run -v $(pwd)/input_images:/app/input_images -v $(pwd)/output_images:/app/output_images image-transparency

Step 3: Serve the Application with an HTTP Server

Next, let’s modify the Python script to serve the functionality via a simple HTTP server using Flask.

  1. Install Flask:bashCopy codepip install flask
  2. Update the Python Script:pythonCopy codefrom flask import Flask, request, send_file from PIL import Image import os app = Flask(__name__) def make_image_transparent(image_path, output_path): image = Image.open(image_path).convert("RGBA") datas = image.getdata() new_data = [] for item in datas: if item[0] > 200 and item[1] > 200 and item[2] > 200: new_data.append((255, 255, 255, 0)) else: new_data.append(item) image.putdata(new_data) image.save(output_path) @app.route('/process', methods=['POST']) def process_image(): file = request.files['file'] input_path = os.path.join('input_images', file.filename) output_path = os.path.join('output_images', 'transparent_' + file.filename) file.save(input_path) make_image_transparent(input_path, output_path) return send_file(output_path, mimetype='image/png') if __name__ == "__main__": os.makedirs('input_images', exist_ok=True) os.makedirs('output_images', exist_ok=True) app.run(host='0.0.0.0', port=80)

Update the Dockerfile to install Flask and run the Flask app:

DockerfileCopy code# Use an official Python runtime as a parent image
FROM python:3.9-slim

# Set the working directory
WORKDIR /app

# Copy the current directory contents into the container
COPY . /app

# Install any needed packages specified in requirements.txt
RUN pip install --no-cache-dir pillow flask

# Make port 80 available to the world outside this container
EXPOSE 80

# Run app.py when the container launches
CMD ["python", "make_transparent.py"]

Step 4: Deploy to Kubernetes

Now, let’s deploy this containerized application to a Kubernetes cluster.

  1. Create a Kubernetes Deployment and Service:deployment.yaml:yamlCopy codeapiVersion: apps/v1 kind: Deployment metadata: name: image-transparency-deployment spec: replicas: 3 selector: matchLabels: app: image-transparency template: metadata: labels: app: image-transparency spec: containers: - name: image-transparency image: image-transparency:latest ports: - containerPort: 80 service.yaml:yamlCopy codeapiVersion: v1 kind: Service metadata: name: image-transparency-service spec: selector: app: image-transparency ports: - protocol: TCP port: 80 targetPort: 80 type: LoadBalancer
  2. Deploy to Kubernetes:bashCopy codekubectl apply -f deployment.yaml kubectl apply -f service.yaml
  3. Access the Service: Once the service is running, you can send a POST request to the /process endpoint with an image file to make it transparent.

Conclusion

By following these steps, you have successfully created a Python application that makes images transparent, containerized it with Docker, and deployed it to a Kubernetes cluster. This process demonstrates the power of combining DevOps tools and practices to build scalable and efficient applications. Happy coding!

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top