如何使用 Node.js 生成 AI 圖片
Node.js 技術相關|AI 應用開發
簡介
隨著人工智慧技術的快速發展,AI 圖片生成已經成為許多應用程式的重要功能。本教學將介紹如何使用 Node.js 透過 API 來程式化生成 AI 圖片,讓您的應用程式具備強大的圖片生成能力。
什麼是 AI 圖片生成?
AI 圖片生成是指利用人工智慧模型,根據文字描述(prompt)自動生成對應的圖片。這項技術可以應用於:
- 自動化內容創作
- 電子商務產品圖片生成
- 社群媒體圖片素材製作
- 遊戲和應用程式資源生成
- 個人化頭像和大頭照製作
使用 AI Photo Generator API
我們將使用 AI Photo Generator 作為範例,展示如何在 Node.js 中整合 AI 圖片生成功能。這個 API 提供了簡單易用的介面來生成高品質的 AI 圖片。
準備工作
在開始之前,請確保您已經:
- 安裝 Node.js(建議版本 18 或以上)
- 註冊 AI Photo Generator 帳號並取得 API Token
- 建立一個新的 Node.js 專案
安裝相依套件
首先,我們需要安裝用於發送 HTTP 請求的套件。您可以使用內建的 fetch(Node.js 18+)或安裝 node-fetch:
npm init -y
npm install node-fetch程式碼範例
以下是使用 Node.js 呼叫 AI Photo Generator API 的完整範例:
使用 async/await 的現代寫法
// generateImage.js
const API_URL = 'https://www.aiphotogenerator.net/api/images/generate';
const API_TOKEN = 'YOUR_API_TOKEN'; // 請替換為您的 API Token
async function generateImage(prompt, options = {}) {
const {
width = 1024,
height = 1024,
model = 'flux-1',
count = 1
} = options;
try {
const response = await fetch(API_URL, {
method: 'POST',
headers: {
'Authorization': `Bearer ${API_TOKEN}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
prompt,
width,
height,
model,
count
})
});
if (!response.ok) {
throw new Error(`API 請求失敗: ${response.status}`);
}
const data = await response.json();
return data;
} catch (error) {
console.error('生成圖片時發生錯誤:', error.message);
throw error;
}
}
// 使用範例
async function main() {
try {
const result = await generateImage(
'A professional headshot of a business executive in a modern office',
{
width: 1024,
height: 1024,
model: 'flux-1',
count: 1
}
);
console.log('圖片生成成功!');
console.log('結果:', JSON.stringify(result, null, 2));
} catch (error) {
console.error('執行失敗:', error);
}
}
main();使用 node-fetch 的替代方案(適用於舊版 Node.js)
// generateImage-legacy.js
const fetch = require('node-fetch');
const API_URL = 'https://www.aiphotogenerator.net/api/images/generate';
const API_TOKEN = 'YOUR_API_TOKEN';
async function generateImage(prompt, options = {}) {
const {
width = 1024,
height = 1024,
model = 'flux-1',
count = 1
} = options;
const response = await fetch(API_URL, {
method: 'POST',
headers: {
'Authorization': `Bearer ${API_TOKEN}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
prompt,
width,
height,
model,
count
})
});
if (!response.ok) {
const errorText = await response.text();
throw new Error(`API 錯誤 (${response.status}): ${errorText}`);
}
return response.json();
}
module.exports = { generateImage };API 參數說明
| 參數 | 類型 | 說明 |
|---|---|---|
prompt | string | 圖片描述文字,描述您想要生成的圖片內容 |
width | number | 圖片寬度(像素) |
height | number | 圖片高度(像素) |
model | string | 使用的 AI 模型(例如:flux-1) |
count | number | 要生成的圖片數量 |
進階用法:批量生成圖片
// batchGenerate.js
async function batchGenerateImages(prompts) {
const results = [];
for (const prompt of prompts) {
console.log(`正在生成: ${prompt.substring(0, 50)}...`);
const result = await generateImage(prompt);
results.push(result);
// 加入延遲以避免 API 限制
await new Promise(resolve => setTimeout(resolve, 1000));
}
return results;
}
// 使用範例
const prompts = [
'一隻可愛的柴犬在公園裡玩耍',
'台北101大樓的夜景',
'一杯精緻的珍珠奶茶'
];
batchGenerateImages(prompts)
.then(results => console.log('所有圖片生成完成!', results))
.catch(error => console.error('批量生成失敗:', error));錯誤處理最佳實踐
async function generateImageWithRetry(prompt, options = {}, maxRetries = 3) {
for (let attempt = 1; attempt <= maxRetries; attempt++) {
try {
return await generateImage(prompt, options);
} catch (error) {
console.warn(`嘗試 ${attempt}/${maxRetries} 失敗:`, error.message);
if (attempt === maxRetries) {
throw new Error(`在 ${maxRetries} 次嘗試後仍然失敗`);
}
// 指數退避等待
const waitTime = Math.pow(2, attempt) * 1000;
console.log(`等待 ${waitTime}ms 後重試...`);
await new Promise(resolve => setTimeout(resolve, waitTime));
}
}
}安全性注意事項
- 請勿將 API Token 硬編碼在程式碼中,建議使用環境變數
- 使用
dotenv套件來管理環境變數 - 確保 API Token 不會被提交到版本控制系統
// 使用環境變數
require('dotenv').config();
const API_TOKEN = process.env.AI_PHOTO_GENERATOR_TOKEN;
if (!API_TOKEN) {
throw new Error('請設定 AI_PHOTO_GENERATOR_TOKEN 環境變數');
}總結
透過本教學,您已經學會如何使用 Node.js 整合 AI 圖片生成 API。這項技術可以大幅提升您應用程式的功能性,為使用者提供更豐富的體驗。如果您想了解更多關於 AI 圖片生成的資訊,歡迎造訪 AI Photo Generator 官方網站。