<!DOCTYPE html>
<html lang="zh-TW">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>圖片生成器</title>
<style>
body {
font-family: Arial, sans-serif;
max-width: 800px;
margin: 0 auto;
padding: 20px;
text-align: center;
}
input, button {
padding: 10px;
margin: 10px;
font-size: 16px;
}
#imageOutput img {
max-width: 100%;
margin-top: 20px;
}
#errorMessage {
color: red;
display: none;
margin-top: 10px;
}
</style>
</head>
<body>
<h1>輸入文字生成圖片</h1>
<div>
<input type="text" id="apiKeyInput" placeholder="輸入 OpenAI API Key" style="width: 300px;">
</div>
<div>
<input type="text" id="promptInput" placeholder="輸入圖片描述(例如:一隻貓在月球)" style="width: 300px;">
<button onclick="generateImage()">生成圖片</button>
</div>
<div id="errorMessage"></div>
<div id="imageOutput"></div>
<script>
async function generateImage() {
const apiKey = document.getElementById('apiKeyInput').value.trim();
const prompt = document.getElementById('promptInput').value.trim();
const errorMessage = document.getElementById('errorMessage');
const imageOutput = document.getElementById('imageOutput');
// 清空錯誤訊息和圖片輸出
errorMessage.style.display = 'none';
errorMessage.textContent = '';
imageOutput.innerHTML = '';
// 驗證輸入
if (!apiKey) {
errorMessage.textContent = '請輸入 OpenAI API Key!';
errorMessage.style.display = 'block';
return;
}
if (!prompt) {
errorMessage.textContent = '請輸入圖片描述!';
errorMessage.style.display = 'block';
return;
}
try {
const response = await fetch('https://api.openai.com/v1/images/generations', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${apiKey}`
},
body: JSON.stringify({
model: 'dall-e-3',
prompt: prompt,
n: 1,
size: '1024x1024'
})
});
if (!response.ok) {
throw new Error(`API 錯誤: ${response.statusText}`);
}
const data = await response.json();
const imageUrl = data.data[0].url;
imageOutput.innerHTML = `<img src="${imageUrl}" alt="Generated Image">`;
} catch (error) {
errorMessage.textContent = `生成圖片失敗: ${error.message}`;
errorMessage.style.display = 'block';
console.error('錯誤:', error);
}
}
</script>
</body>
</html>