长图优化,防止出错

This commit is contained in:
liuwei
2026-02-03 15:27:51 +08:00
parent 4cac7c04a0
commit e9b6eff251

View File

@@ -154,14 +154,15 @@ class DouyinParserPlugin(MessagePluginInterface):
img_bytes_list.append(b)
if not img_bytes_list:
return False, "下载图片失败"
merged = self._merge_images_vertical(img_bytes_list, 1242)
if not merged:
merged_pages = self._merge_images_vertical_paged(img_bytes_list, 1242, 18000)
if not merged_pages:
return False, "图片合并失败"
title = media_info.get('title') or ""
if len(title) > 0:
await self.bot.send_text_message((roomid if roomid else sender), title)
await self.bot.send_image_message((roomid if roomid else sender), merged)
return True, "发送合并图片成功"
for page in merged_pages:
await self.bot.send_image_message((roomid if roomid else sender), page)
return True, f"发送合并图片成功({len(merged_pages)}页)"
else:
video_url = media_info.get('url', '')
title = media_info.get('title', '无标题')
@@ -438,3 +439,47 @@ class DouyinParserPlugin(MessagePluginInterface):
return output.getvalue()
except Exception:
return None
def _merge_images_vertical_paged(self, images: List[bytes], target_width: int = 1242, max_total_height: int = 18000) -> Optional[List[bytes]]:
try:
outputs: List[bytes] = []
current_images: List[Image.Image] = []
current_height = 0
for b in images:
try:
img = Image.open(io.BytesIO(b))
if img.mode in ("RGBA", "P"):
img = img.convert("RGB")
w, h = img.size
if w != target_width:
ratio = target_width / float(w)
img = img.resize((target_width, int(h * ratio)))
ih = img.size[1]
except Exception:
continue
if current_images and current_height + ih > max_total_height:
merged = Image.new("RGB", (target_width, current_height))
y = 0
for im in current_images:
merged.paste(im, (0, y))
y += im.size[1]
out = io.BytesIO()
merged.save(out, format="JPEG", quality=85)
outputs.append(out.getvalue())
current_images = [img]
current_height = img.size[1]
else:
current_images.append(img)
current_height += ih
if current_images:
merged = Image.new("RGB", (target_width, current_height))
y = 0
for im in current_images:
merged.paste(im, (0, y))
y += im.size[1]
out = io.BytesIO()
merged.save(out, format="JPEG", quality=85)
outputs.append(out.getvalue())
return outputs if outputs else None
except Exception:
return None