Skip to content

Commit 04dcb81

Browse files
authored
Added product image generator and replicate examples (#2511)
* Added nano banana task * Renamed the file and updated docs.json * Added product imgae generator demo project * Removed old section * Code tweak
1 parent 0f9b83d commit 04dcb81

File tree

4 files changed

+174
-0
lines changed

4 files changed

+174
-0
lines changed

docs/docs.json

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -343,6 +343,7 @@
343343
"guides/example-projects/mastra-agents-with-memory",
344344
"guides/example-projects/meme-generator-human-in-the-loop",
345345
"guides/example-projects/openai-agents-sdk-typescript-playground",
346+
"guides/example-projects/product-image-generator",
346347
"guides/example-projects/realtime-csv-importer",
347348
"guides/example-projects/realtime-fal-ai",
348349
"guides/example-projects/turborepo-monorepo-prisma",
@@ -376,6 +377,7 @@
376377
"guides/examples/puppeteer",
377378
"guides/examples/react-pdf",
378379
"guides/examples/react-email",
380+
"guides/examples/replicate-image-generation",
379381
"guides/examples/resend-email-sequence",
380382
"guides/examples/satori",
381383
"guides/examples/scrape-hacker-news",
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
---
2+
title: "Product image generator using Replicate and Trigger.dev"
3+
sidebarTitle: "Product image generator"
4+
description: "AI-powered product image generator that transforms basic product photos into professional marketing shots using Replicate's image generation models"
5+
---
6+
7+
## Overview
8+
9+
This project demonstrates how to build an AI-powered product image generator that transforms basic product photos into professional marketing shots. Users upload a product image and receive three professionally styled variations: clean product shots, lifestyle scenes, and hero shots with dramatic lighting.
10+
11+
## Video
12+
13+
<video
14+
controls
15+
className="w-full aspect-video"
16+
src="https://content.trigger.dev/product-image-generator-example.mp4"
17+
/>
18+
19+
## GitHub repo
20+
21+
Clone this repo and follow the instructions in the `README.md` file to get started.
22+
23+
<Card
24+
title="View the product image generator repo"
25+
icon="GitHub"
26+
href="https://github.com/triggerdotdev/examples/tree/main/product-image-generator"
27+
>
28+
Click here to view the full code in our examples repository on GitHub. You can fork it and use it
29+
as a starting point for your project.
30+
</Card>
31+
32+
## Tech stack
33+
34+
- [**Next.js**](https://nextjs.org/) – frontend React framework
35+
- [**Replicate**](https://replicate.com/docs) – AI image generation using the `google/nano-banana` image-to-image model
36+
- [**UploadThing**](https://uploadthing.com/) – file upload management and server callbacks
37+
- [**Cloudflare R2**](https://developers.cloudflare.com/r2/) – scalable image storage with public URLs
38+
39+
## How it works
40+
41+
The application orchestrates image generation through two main tasks: [`generateImages`](https://github.com/triggerdotdev/examples/blob/main/product-image-generator/app/trigger/generate-images.ts) coordinates batch processing, while [`generateImage`](https://github.com/triggerdotdev/examples/blob/main/product-image-generator/app/trigger/generate-images.ts) handles individual style generation.
42+
43+
Each generation task enhances prompts with style-specific instructions, calls Replicate's `google/nano-banana` image-to-image model, creates waitpoint tokens for async webhook handling, and uploads results to Cloudflare R2. The frontend displays real-time progress updates via React hooks as tasks complete.
44+
45+
Style presets include clean product shots (white background), lifestyle scenes (person holding product), and hero shots (dramatic lighting).
46+
47+
## Relevant code
48+
49+
- **Image generation tasks** – batch processing with waitpoints for Replicate webhook callbacks ([`app/trigger/generate-images.ts`](https://github.com/triggerdotdev/examples/blob/main/product-image-generator/app/trigger/generate-images.ts))
50+
- **Upload handler** – UploadThing integration that triggers batch generation ([`app/api/uploadthing/core.ts`](https://github.com/triggerdotdev/examples/blob/main/product-image-generator/app/api/uploadthing/core.ts))
51+
- **Real-time progress UI** – live task updates using React hooks ([`app/components/GeneratedCard.tsx`](https://github.com/triggerdotdev/examples/blob/main/product-image-generator/app/components/GeneratedCard.tsx))
52+
- **Custom prompt interface** – user-defined style generation ([`app/components/CustomPromptCard.tsx`](https://github.com/triggerdotdev/examples/blob/main/product-image-generator/app/components/CustomPromptCard.tsx))
53+
- **Main app component** – layout and state management ([`app/ProductImageGenerator.tsx`](https://github.com/triggerdotdev/examples/blob/main/product-image-generator/app/ProductImageGenerator.tsx))
54+
55+
## Learn more
56+
57+
- [**Waitpoints**](/wait-for-token) – pause tasks for async webhook callbacks
58+
- [**React hooks**](/realtime/react-hooks/overview) – real-time task updates and frontend integration
59+
- [**Batch operations**](/triggering#tasks-batchtrigger) – parallel task execution patterns
60+
- [**Replicate API**](https://replicate.com/docs/get-started/nextjs) – AI model integration
61+
- [**UploadThing**](https://docs.uploadthing.com/) – file upload handling and server callbacks
Lines changed: 109 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,109 @@
1+
---
2+
title: "Image-to-image generation using Replicate and nano-banana"
3+
sidebarTitle: "Replicate image generation"
4+
description: "Learn how to generate images from source image URLs using Replicate and Trigger.dev."
5+
---
6+
7+
## Overview
8+
9+
This example demonstrates how to use Trigger.dev to generate images from source image URLs using [Replicate](https://replicate.com/), the [nano-banana-image-to-image](https://replicate.com/meta/nano-banana-image-to-image) model.
10+
11+
## Task code
12+
13+
```tsx trigger/generateImage.tsx
14+
import { PutObjectCommand, S3Client } from "@aws-sdk/client-s3";
15+
import { task, wait } from "@trigger.dev/sdk";
16+
import Replicate, { Prediction } from "replicate";
17+
18+
// Initialize clients
19+
const replicate = new Replicate({
20+
auth: process.env.REPLICATE_API_TOKEN,
21+
});
22+
23+
const s3Client = new S3Client({
24+
region: "auto",
25+
endpoint: process.env.R2_ENDPOINT,
26+
credentials: {
27+
accessKeyId: process.env.R2_ACCESS_KEY_ID ?? "",
28+
secretAccessKey: process.env.R2_SECRET_ACCESS_KEY ?? "",
29+
},
30+
});
31+
32+
const model = "google/nano-banana";
33+
34+
export const generateImageAndUploadToR2 = task({
35+
id: "generate-image-and-upload-to-r2",
36+
run: async (payload: { prompt: string; imageUrl: string }) => {
37+
const { prompt, imageUrl } = payload;
38+
39+
const token = await wait.createToken({
40+
timeout: "10m",
41+
});
42+
43+
// Use Flux with structured prompt
44+
const output = await replicate.predictions.create({
45+
model: model,
46+
input: { prompt, image_input: [imageUrl] },
47+
// pass the provided URL to Replicate's webhook, so they can "callback"
48+
webhook: token.url,
49+
webhook_events_filter: ["completed"],
50+
});
51+
52+
const result = await wait.forToken<Prediction>(token).unwrap();
53+
// unwrap() throws a timeout error or returns the result 👆
54+
55+
if (!result.ok) {
56+
throw new Error("Failed to create prediction");
57+
}
58+
59+
const generatedImageUrl = result.output.output;
60+
61+
const image = await fetch(generatedImageUrl);
62+
const imageBuffer = Buffer.from(await image.arrayBuffer());
63+
64+
const base64Image = Buffer.from(imageBuffer).toString("base64");
65+
66+
const timestamp = Date.now();
67+
const filename = `generated-${timestamp}.png`;
68+
69+
// Generate unique key for R2
70+
const sanitizedFileName = filename.replace(/[^a-zA-Z0-9.-]/g, "_");
71+
const r2Key = `uploaded-images/${timestamp}-${sanitizedFileName}`;
72+
73+
const uploadParams = {
74+
Bucket: process.env.R2_BUCKET,
75+
Key: r2Key,
76+
Body: imageBuffer,
77+
ContentType: "image/png",
78+
// Add cache control for better performance
79+
CacheControl: "public, max-age=31536000", // 1 year
80+
};
81+
82+
const uploadResult = await s3Client.send(new PutObjectCommand(uploadParams));
83+
84+
// Construct the public URL using the R2_PUBLIC_URL env var
85+
const publicUrl = `${process.env.R2_PUBLIC_URL}/${r2Key}`;
86+
87+
return {
88+
success: true,
89+
publicUrl,
90+
originalPrompt: prompt,
91+
sourceImageUrl: imageUrl,
92+
};
93+
},
94+
});
95+
```
96+
97+
## Environment variables
98+
99+
You will need to set the following environment variables:
100+
101+
```
102+
TRIGGER_SECRET_KEY=<your-trigger-secret-key>
103+
REPLICATE_API_TOKEN=<your-replicate-api-token>
104+
R2_ENDPOINT=<your-r2-endpoint>
105+
R2_ACCESS_KEY_ID=<your-r2-access-key-id>
106+
R2_SECRET_ACCESS_KEY=<your-r2-secret-access-key>
107+
R2_BUCKET=<your-r2-bucket>
108+
R2_PUBLIC_URL=<your-r2-public-url>
109+
```

docs/guides/introduction.mdx

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,7 @@ Example projects are full projects with example repos you can fork and use. Thes
5252
| [Mastra agents with memory](/guides/example-projects/mastra-agents-with-memory) | Use Mastra to create a weather agent that can collect live weather data and generate clothing recommendations. || [View the repo](https://github.com/triggerdotdev/examples/tree/main/mastra-agents) |
5353
| [OpenAI Agents SDK for Python guardrails](/guides/example-projects/openai-agent-sdk-guardrails) | Use the OpenAI Agents SDK for Python to create a guardrails system for your AI agents. || [View the repo](https://github.com/triggerdotdev/examples/tree/main/openai-agent-sdk-guardrails-examples) |
5454
| [OpenAI Agents SDK for TypeScript playground](/guides/example-projects/openai-agents-sdk-typescript-playground) | A playground containing 7 AI agents using the OpenAI Agents SDK for TypeScript with Trigger.dev. || [View the repo](https://github.com/triggerdotdev/examples/tree/main/openai-agents-sdk-with-trigger-playground) |
55+
| [Product image generator](/guides/example-projects/product-image-generator) | Transform basic product photos into professional marketing shots using Replicate's image generation models. | Next.js | [View the repo](https://github.com/triggerdotdev/examples/tree/main/product-image-generator) |
5556
| [Python web crawler](/guides/python/python-crawl4ai) | Use Python, Crawl4AI and Playwright to create a headless web crawler with Trigger.dev. || [View the repo](https://github.com/triggerdotdev/examples/tree/main/python-crawl4ai) |
5657
| [Realtime CSV Importer](/guides/example-projects/realtime-csv-importer) | Upload a CSV file and see the progress of the task streamed to the frontend. | Next.js | [View the repo](https://github.com/triggerdotdev/examples/tree/main/realtime-csv-importer) |
5758
| [Realtime Fal.ai image generation](/guides/example-projects/realtime-fal-ai) | Generate an image from a prompt using Fal.ai and show the progress of the task on the frontend using Realtime. | Next.js | [View the repo](https://github.com/triggerdotdev/examples/tree/main/realtime-fal-ai-image-generation) |
@@ -79,6 +80,7 @@ Task code you can copy and paste to use in your project. They can all be extende
7980
| [React email](/guides/examples/react-email) | Send an email using React Email. |
8081
| [React to PDF](/guides/examples/react-pdf) | Use `react-pdf` to generate a PDF and save it to Cloudflare R2. |
8182
| [Resend email sequence](/guides/examples/resend-email-sequence) | Send a sequence of emails over several days using Resend with Trigger.dev. |
83+
| [Replicate image generation](/guides/examples/replicate-image-generation) | Learn how to generate images from source image URLs using Replicate and Trigger.dev. |
8284
| [Satori](/guides/examples/satori) | Generate OG images using React Satori. |
8385
| [Scrape Hacker News](/guides/examples/scrape-hacker-news) | Scrape Hacker News using BrowserBase and Puppeteer, summarize the articles with ChatGPT and send an email of the summary every weekday using Resend. |
8486
| [Sentry error tracking](/guides/examples/sentry-error-tracking) | Automatically send errors to Sentry from your tasks. |

0 commit comments

Comments
 (0)