惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

B
Blog RSS Feed
量子位
Y
Y Combinator Blog
大猫的无限游戏
大猫的无限游戏
B
Blog
U
Unit 42
C
Check Point Blog
I
InfoQ
aimingoo的专栏
aimingoo的专栏
雷峰网
雷峰网
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
博客园 - 【当耐特】
人人都是产品经理
人人都是产品经理
The Cloudflare Blog
H
Help Net Security
MongoDB | Blog
MongoDB | Blog
博客园 - Franky
H
Hackread – Cybersecurity News, Data Breaches, AI and More
J
Java Code Geeks
Microsoft Azure Blog
Microsoft Azure Blog
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
云风的 BLOG
云风的 BLOG
宝玉的分享
宝玉的分享
爱范儿
爱范儿

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
How I Built an AI Image Studio with 9 Tools Using PHP 8.4...
Zihang Dong · 2026-04-29 · via DEV Community

Zihang Dong 董子航

I just launched 24picture — an all-in-one AI image studio with 9 specialized tools. Built with PHP 8.4, MySQL 8.4, and Nginx.

In this post I'll share the architecture decisions, the nastiest bug I encountered, and what I learned shipping a real AI product.

What I Built

Instead of yet another "text to image" wrapper, I built a platform with 9 tools:

  • Text to Image — 3 AI models, up to 4K resolution
  • Image to Image — transform existing photos
  • AI Upscale — enhance images up to 4K
  • AI Model — virtual model photography
  • AI Tattoo Design — custom flash sheets in 7 tattoo styles
  • AI Sticker Maker — die-cut stickers from text prompts
  • Photo to Anime — turn photos into anime art
  • AI Photo Notes — stylized photo annotations
  • AI Polish — one-click prompt enhancement via DeepSeek API

All tools share the same backend — one create.php to submit jobs, one status.php to poll results. The frontend does prompt template assembly per tool.

Tech Stack

Layer Tech
Backend PHP 8.4 (no framework)
Database MySQL 8.4
Web Server Nginx
CDN / Security Cloudflare
AI Models Nano Banana 2, NB Pro, GPT Image (via kie.ai API)
Prompt Enhancement DeepSeek API
Email Resend API (magic link auth)
Payments Creem (credit-based, no subscription)

Why PHP with No Framework?

Controversial take: for an API-centric product with ~15 endpoints, a framework adds more complexity than it solves. Raw PHP 8.4 with PDO, strict typing, and a single config.php bootstrap keeps things dead simple. The entire backend is about 2,000 lines of code.

Architecture: One Backend, Nine Tools

The key design decision was making all 9 tools share the same backend pipeline:

Frontend (per-tool UI)
  → assembles prompt from user inputs
  → POST /api/generate/create.php
    → deduct credits
    → call AI API
    → save generation record
  → poll GET /api/generate/status.php
    → check AI API status
    → on success: save result, create thumbnail, send email
    → return result to frontend

Enter fullscreen mode Exit fullscreen mode

Adding a new tool means creating a new HTML page that assembles a different prompt template. Zero backend changes. I went from 3 tools to 9 in a single day using this pattern.

The Nastiest Bug: 4K Thumbnails Crashing PHP

This one took me a while to figure out. Users would generate a 4K image successfully, but the status endpoint would return a 500 error — every single time. The image was ready on the AI provider's side, but our server kept crashing when trying to process it.

The Problem

When a generation completes, status.php creates a thumbnail using PHP's GD library:

$src = imagecreatefromstring($imgData);

Enter fullscreen mode Exit fullscreen mode

For a 4K image (roughly 4096 × 2304 pixels), GD needs to hold the uncompressed bitmap in memory:

4096 × 2304 × 4 bytes (RGBA) × 2.5 (overhead) ≈ 94 MB

Enter fullscreen mode Exit fullscreen mode

PHP's default memory limit is 128MB. With the rest of the script's memory usage, this pushed it over the edge. The fatal memory error killed the script before the database was updated, so the next poll attempt would try the same thing — an infinite crash loop.

The Fix

Three changes:

1. Update the database FIRST, before attempting the thumbnail:

// Mark as success immediately
$stmt = $db->prepare('UPDATE generations SET status = "success", 
    result_url = ?, completed_at = NOW() WHERE task_id = ?');
$stmt->execute([$resultUrl, $taskId]);

// THEN try thumbnail (best-effort)
try {
    $thumbUrl = createThumbnail($resultUrl, $gen['id']);
} catch (\Throwable $e) {
    error_log("Thumbnail failed: " . $e->getMessage());
}

Enter fullscreen mode Exit fullscreen mode

Even if the thumbnail crashes, the next poll returns cached success.

2. Memory estimation before loading the image:

$info = getimagesizefromstring($imgData);
$needed = $info[0] * $info[1] * ($info['channels'] ?? 4) 
          * ($info['bits'] ?? 8) / 8 * 2.5;
if ($needed > 128 * 1024 * 1024) {
    return null; // skip thumbnail for huge images
}
ini_set('memory_limit', '256M');

Enter fullscreen mode Exit fullscreen mode

3. Wrap everything after the DB update in try-catch so no post-processing error can block the response.

Lesson Learned

Always persist your state change before doing expensive side effects. If your script can crash during step N, make sure steps 1 through N-1 are already committed.

This applies to any pipeline: payment processing, webhook handling, email sending — commit the critical state first.

Credit System Design

I chose pay-as-you-go credits instead of subscriptions:

Model 1K 2K 4K
Nano Banana 2 10 15 24
NB Pro 24 24 30
GPT Image 8 13 20

Credits never expire. Free credits on signup. This removes the "am I getting my money's worth?" anxiety that subscriptions create.

For the backend, credit deduction uses a simple SELECT ... FOR UPDATE lock to prevent race conditions:

$db->beginTransaction();
$stmt = $db->prepare('SELECT credits FROM users WHERE id = ? FOR UPDATE');
$stmt->execute([$userId]);
$credits = (int)$stmt->fetchColumn();

if ($credits < $cost) {
    $db->rollBack();
    return error('Insufficient credits');
}

$stmt = $db->prepare('UPDATE users SET credits = credits - ? WHERE id = ?');
$stmt->execute([$cost, $userId]);
$db->commit();

Enter fullscreen mode Exit fullscreen mode

Important: release the lock before calling the external AI API. Don't hold database locks across network calls.

Security Checklist (Things I Almost Forgot)

A quick list for anyone shipping a similar product:

  • ✅ Session cookies: HttpOnly, Secure, SameSite=Lax
  • ✅ File upload validation: getimagesize() server-side, not just MIME
  • ✅ Download proxy: whitelist allowed domains to prevent SSRF
  • ✅ Rate limiting on contact forms (IP-based)
  • ✅ XSS escaping on all user-generated content in the frontend
  • ✅ SQL injection prevention: parameterized queries everywhere
  • ✅ Feature whitelist: validate feature parameter against allowed values

What's Next

The product is live at 24picture.com. Currently focused on:

  • Growing organic traffic through SEO and content
  • Adding more specialized tools (AI Interior Design, AI Product Photo)
  • Building a Chrome extension for right-click AI upscale

If you're building something similar, I hope this post saves you from the 4K thumbnail crash and the database lock pitfall. Happy to answer questions in the comments!


If you want to try it out, there are free credits on signup — no card required: 24picture.com