feat: 优化图片生成处理,支持直接发送B64数据

pull/1039/head
JieIYu 2025-06-08 10:21:57 +08:00
parent 4f7285d468
commit 6d4e694cad
1 changed files with 52 additions and 32 deletions

View File

@ -145,9 +145,19 @@ class PicAction(PluginAction):
result = f"图片生成服务遇到意外问题: {str(e)[:100]}" result = f"图片生成服务遇到意外问题: {str(e)[:100]}"
if success: if success:
# 如果返回的是Base64数据以"iVBORw"等开头),直接使用
if result.startswith(("iVBORw", "/9j/", "UklGR", "R0lGOD")): # 常见图片格式的Base64前缀
logger.info(f"{self.log_prefix} 获取到Base64图片数据直接发送")
send_success = await self.send_message(type="image", data=result)
if send_success:
await self.send_message_by_expressor("图片表情已发送!")
return True, "图片表情已发送(Base64)"
else:
await self.send_message_by_expressor("图片已处理为Base64但作为表情发送失败了。")
return False, "图片表情发送失败 (Base64)"
else: # 否则认为是URL
image_url = result image_url = result
logger.info(f"{self.log_prefix} 图片URL获取成功: {image_url[:70]}... 下载并编码.") logger.info(f"{self.log_prefix} 图片URL获取成功: {image_url[:70]}... 下载并编码.")
try: try:
encode_success, encode_result = await asyncio.to_thread(self._download_and_encode_base64, image_url) encode_success, encode_result = await asyncio.to_thread(self._download_and_encode_base64, image_url)
except Exception as e: except Exception as e:
@ -155,7 +165,6 @@ class PicAction(PluginAction):
traceback.print_exc() traceback.print_exc()
encode_success = False encode_success = False
encode_result = f"图片下载或编码时发生内部错误: {str(e)[:100]}" encode_result = f"图片下载或编码时发生内部错误: {str(e)[:100]}"
if encode_success: if encode_success:
base64_image_string = encode_result base64_image_string = encode_result
send_success = await self.send_message(type="image", data=base64_image_string) send_success = await self.send_message(type="image", data=base64_image_string)
@ -203,7 +212,7 @@ class PicAction(PluginAction):
payload_dict = { payload_dict = {
"model": model, "model": model,
"prompt": prompt, "prompt": prompt,
"response_format": "url", #"response_format": "b64_json",# gpt-image-1 无法使用 url 返回为 “b64_json",豆包默认返回为 "url"
"size": size, "size": size,
"guidance_scale": guidance_scale, "guidance_scale": guidance_scale,
"watermark": watermark, "watermark": watermark,
@ -218,7 +227,7 @@ class PicAction(PluginAction):
"Content-Type": "application/json", "Content-Type": "application/json",
"Accept": "application/json", "Accept": "application/json",
"Authorization": f"Bearer {generate_api_key}", "Authorization": f"Bearer {generate_api_key}",
} }# gpt 或其他模型密钥要删除Bearer ’前缀
logger.info(f"{self.log_prefix} (HTTP) 发起图片请求: {model}, Prompt: {prompt[:30]}... To: {endpoint}") logger.info(f"{self.log_prefix} (HTTP) 发起图片请求: {model}, Prompt: {prompt[:30]}... To: {endpoint}")
logger.debug( logger.debug(
@ -240,7 +249,19 @@ class PicAction(PluginAction):
if 200 <= response_status < 300: if 200 <= response_status < 300:
response_data = json.loads(response_body_str) response_data = json.loads(response_body_str)
# 优先检查Base64数据
if (
isinstance(response_data.get("data"), list)
and response_data["data"]
and isinstance(response_data["data"][0], dict)
and "b64_json" in response_data["data"][0]
):
b64_data = response_data["data"][0]["b64_json"]
logger.info(f"{self.log_prefix} (HTTP) 获取到Base64图片数据长度: {len(b64_data)}")
return True, b64_data # 直接返回Base64字符串
else:
image_url = None image_url = None
if ( if (
isinstance(response_data.get("data"), list) isinstance(response_data.get("data"), list)
and response_data["data"] and response_data["data"]
@ -249,7 +270,6 @@ class PicAction(PluginAction):
image_url = response_data["data"][0].get("url") image_url = response_data["data"][0].get("url")
elif response_data.get("url"): elif response_data.get("url"):
image_url = response_data.get("url") image_url = response_data.get("url")
if image_url: if image_url:
logger.info(f"{self.log_prefix} (HTTP) 图片生成成功URL: {image_url[:70]}...") logger.info(f"{self.log_prefix} (HTTP) 图片生成成功URL: {image_url[:70]}...")
return True, image_url return True, image_url