|
| 1 | +# Image Generation with Pillow Example |
| 2 | + |
| 3 | +This example demonstrates how to build a Python Worker that dynamically generates images using the Pillow (PIL) library. It showcases various image generation techniques perfect for creating dynamic graphics, badges, placeholders, and charts on-the-fly. |
| 4 | + |
| 5 | +## What It Does |
| 6 | + |
| 7 | +The Worker provides four different image generation endpoints: |
| 8 | +1. **Gradient Generator** (`/gradient`) - Creates beautiful gradient images with customizable colors and dimensions |
| 9 | +2. **Badge Generator** (`/badge`) - Generates custom badges or buttons with text |
| 10 | +3. **Placeholder Generator** (`/placeholder`) - Creates placeholder images with dimensions displayed (like placehold.it) |
| 11 | +4. **Chart Generator** (`/chart`) - Produces simple bar charts with custom data |
| 12 | + |
| 13 | +This example showcases how to use the Pillow library in Python Workers to manipulate images, draw shapes, render text, and return binary image data. |
| 14 | + |
| 15 | +## How to Run |
| 16 | + |
| 17 | +First ensure that `uv` is installed: |
| 18 | +https://docs.astral.sh/uv/getting-started/installation/#standalone-installer |
| 19 | + |
| 20 | +Now, if you run `uv run pywrangler dev` within this directory, it should use the config |
| 21 | +in `wrangler.jsonc` to run the example. |
| 22 | + |
| 23 | +```bash |
| 24 | +uv run pywrangler dev |
| 25 | +``` |
| 26 | + |
| 27 | +Then visit: |
| 28 | +- `http://localhost:8787/` - Interactive demo page with all examples |
| 29 | +- `http://localhost:8787/gradient?width=600&height=300&color1=FF6B6B&color2=4ECDC4` - Gradient image |
| 30 | +- `http://localhost:8787/badge?text=Python+Workers&bg_color=2196F3` - Custom badge |
| 31 | +- `http://localhost:8787/placeholder?width=500&height=300` - Placeholder image |
| 32 | +- `http://localhost:8787/chart?values=15,30,25,40,20&labels=Mon,Tue,Wed,Thu,Fri` - Bar chart |
| 33 | + |
| 34 | +## Deployment |
| 35 | + |
| 36 | +Deploy to Cloudflare Workers: |
| 37 | + |
| 38 | +```bash |
| 39 | +uv run pywrangler deploy |
| 40 | +``` |
| 41 | + |
| 42 | +## Key Pillow Features Demonstrated |
| 43 | + |
| 44 | +- **Image Creation** - `Image.new()` for creating blank canvases |
| 45 | +- **Drawing Shapes** - `ImageDraw` for lines, rectangles, and more |
| 46 | +- **Text Rendering** - `ImageFont` and `draw.text()` for adding text |
| 47 | +- **Color Manipulation** - RGB color interpolation for gradients |
| 48 | +- **Binary Output** - Converting images to bytes for HTTP responses |
| 49 | + |
| 50 | +## Learn More |
| 51 | + |
| 52 | +- [Pillow Documentation](https://pillow.readthedocs.io/) |
| 53 | +- [Python Workers Documentation](https://developers.cloudflare.com/workers/languages/python/) |
| 54 | +- [ImageDraw Reference](https://pillow.readthedocs.io/en/stable/reference/ImageDraw.html) |
0 commit comments