2026-05-24 22:47:43 +08:00
|
|
|
package handler
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"encoding/base64"
|
|
|
|
|
"net/http"
|
|
|
|
|
|
2026-05-25 14:31:04 +08:00
|
|
|
"gen2d/internal/logger"
|
2026-05-24 22:47:43 +08:00
|
|
|
"gen2d/internal/model"
|
|
|
|
|
"gen2d/internal/service"
|
|
|
|
|
|
|
|
|
|
"github.com/gin-gonic/gin"
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
// EditImageRequest 图片编辑请求。
|
|
|
|
|
type EditImageRequest struct {
|
2026-05-25 14:31:04 +08:00
|
|
|
Image string `json:"image" binding:"required"` // 底图 base64 编码
|
|
|
|
|
Prompt string `json:"prompt" binding:"required"` // 编辑指令
|
|
|
|
|
Count int `json:"count"` // 生成数量,默认 1
|
2026-05-24 22:47:43 +08:00
|
|
|
}
|
|
|
|
|
|
2026-05-25 12:27:07 +08:00
|
|
|
// editAssetResponse 编辑结果素材(返回 base64)。
|
|
|
|
|
type editAssetResponse struct {
|
|
|
|
|
Data string `json:"data"`
|
|
|
|
|
Format string `json:"format"`
|
|
|
|
|
}
|
|
|
|
|
|
2026-05-24 22:47:43 +08:00
|
|
|
// EditImageResponse 图片编辑响应体。
|
|
|
|
|
type EditImageResponse struct {
|
2026-05-25 12:27:07 +08:00
|
|
|
Assets []editAssetResponse `json:"assets"`
|
2026-05-24 22:47:43 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// EditImage 图片编辑接口,基于已有图片和文本指令生成修改后的图片。
|
|
|
|
|
func EditImage(c *gin.Context) {
|
|
|
|
|
var req EditImageRequest
|
|
|
|
|
if err := c.ShouldBindJSON(&req); err != nil {
|
|
|
|
|
c.JSON(http.StatusBadRequest, model.Fail(http.StatusBadRequest, "参数错误: "+err.Error()))
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
imageData, err := base64.StdEncoding.DecodeString(req.Image)
|
|
|
|
|
if err != nil {
|
2026-05-25 14:31:04 +08:00
|
|
|
c.JSON(http.StatusBadRequest, model.Fail(http.StatusBadRequest, "图片 base64 解码失败"))
|
2026-05-24 22:47:43 +08:00
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
count := req.Count
|
|
|
|
|
if count <= 0 {
|
|
|
|
|
count = 1
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
images, err := service.EditImages(c.Request.Context(), imageData, req.Prompt, count)
|
|
|
|
|
if err != nil {
|
2026-05-25 14:31:04 +08:00
|
|
|
logger.FromCtx(c.Request.Context()).Error("图片编辑失败", "error", err)
|
|
|
|
|
c.JSON(http.StatusInternalServerError, model.Fail(http.StatusInternalServerError, "图片编辑失败"))
|
2026-05-24 22:47:43 +08:00
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
2026-05-25 12:27:07 +08:00
|
|
|
assets := make([]editAssetResponse, len(images))
|
2026-05-24 22:47:43 +08:00
|
|
|
for i, img := range images {
|
2026-05-25 12:27:07 +08:00
|
|
|
assets[i] = editAssetResponse{
|
2026-05-24 22:47:43 +08:00
|
|
|
Data: base64.StdEncoding.EncodeToString(img.Data),
|
|
|
|
|
Format: img.Format,
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
c.JSON(http.StatusOK, model.OK(EditImageResponse{Assets: assets}))
|
|
|
|
|
}
|