feat: 完成图片异步生成

This commit is contained in:
ccnetcore
2025-12-26 23:46:36 +08:00
parent a9267bfc0e
commit 047937af4c
9 changed files with 470 additions and 36 deletions

View File

@@ -966,9 +966,14 @@ public class AiGateWayManager : DomainService
//解析json获取base64字符串
var imageBase64 = GeminiGenerateContentAcquirer.GetImageBase64(data);
//base64字符串存储返回绝对路径用于最后存储
var storeUrl = Base64ToPng(imageBase64, "存储的路径?这个放什么");
//远程调用上传接口将base64转换为URL
var httpClient = LazyServiceProvider.LazyGetRequiredService<IHttpClientFactory>().CreateClient();
var uploadUrl = $"https://ccnetcore.com/prod-api/ai-hub/ai-image/upload-base64";
var content = new StringContent(JsonSerializer.Serialize(imageBase64), Encoding.UTF8, "application/json");
var uploadResponse = await httpClient.PostAsync(uploadUrl, content, cancellationToken);
uploadResponse.EnsureSuccessStatusCode();
var storeUrl = await uploadResponse.Content.ReadAsStringAsync(cancellationToken);
storeUrl = storeUrl.Trim('"'); // 移除JSON字符串的引号
var tokenUsage = new ThorUsageResponse
{
@@ -994,42 +999,12 @@ public class AiGateWayManager : DomainService
await PremiumPackageManager.TryConsumeTokensAsync(userId, totalTokens);
}
//设置存储url
//设置存储base64和url
imageStoreTask.StoreBase64 = imageBase64;
imageStoreTask.SetSuccess(storeUrl);
await _imageStoreTaskRepository.UpdateAsync(imageStoreTask);
}
/// <summary>
/// 将 Base64 字符串转换为 PNG 图片并保存
/// </summary>
/// <param name="base64String">Base64 字符串(可以包含或不包含 data:image/png;base64, 前缀)</param>
/// <param name="outputPath">输出文件路径</param>
private string Base64ToPng(string base64String, string outputPath)
{
try
{
// 移除可能存在的 data URI scheme 前缀
if (base64String.Contains(","))
{
base64String = base64String.Substring(base64String.IndexOf(",") + 1);
}
// 将 base64 字符串转换为字节数组
byte[] imageBytes = Convert.FromBase64String(base64String);
// 将字节数组写入文件
File.WriteAllBytes(outputPath, imageBytes);
}
catch (Exception ex)
{
throw new UserFriendlyException("gemini Base64转图像失败", innerException: ex);
}
//todo
//路径拼接一下?
return outputPath;
}
#region Http响应
private static readonly byte[] EventPrefix = "event: "u8.ToArray();