照片合成功能(1)
在這篇文章中,我們將介紹如何在前端實現照片合成功能,重點是如何將使用者上傳的圖片與提示詞傳送到後端 API,並顯示合成結果。
/api/mix-image API
在前端,使用者可以透過檔案上傳區域選擇圖片,並輸入提示詞。
const files = Array.from(document.getElementById('photo-upload').files);
const prompt = document.getElementById('prompt-input').value.trim();
將圖片與提示詞加入 FormData,然後使用 fetch 發送 POST 請求到後端的 /api/mix-images API。
const formData = new FormData();
files.forEach(file => formData.append('images', file));
if (prompt) formData.append('prompt', prompt);
const response = await fetch('/api/mix-images', {
method: 'POST',
body: formData,
});
const result = await response.json();
後端回應的 JSON 可能包含 image_url(合成圖片的路徑)或 error 訊息。前端根據回應動態更新結果區域。
if (result.error) {
showError(result.error);
} else if (result.image_url) {
showResultImage(result.image_url);
}
function showResultImage(url) {
const gallery = document.getElementById('result-gallery');
gallery.innerHTML = `<img src="${url}" alt="合成結果" style="max-width:400px;">`;
document.getElementById('download-btn').onclick = () => {
window.open(url, '_blank');
};
}
這篇文章介紹了照片合成功能的前端實作,重點在於如何將圖片與提示詞傳送到後端,並顯示合成結果。下一篇文章,我們將專注於後端的圖片合成邏輯,並使用 AI 模型來處理圖片。