解决句柄占用问题。

This commit is contained in:
liuwei
2025-05-26 10:08:29 +08:00
parent 9731589d6d
commit 3832997ac5
3 changed files with 58 additions and 61 deletions

View File

@@ -150,10 +150,9 @@ def download_image(img_url, folder_path, img_index, max_retries=3):
time.sleep(2 * (attempt + 1))
continue
img = Image.open(BytesIO(response.content)).convert('RGB')
with Image.open(BytesIO(response.content)).convert('RGB') as img:
img_name = f"{img_index:03d}.jpg"
img_path = os.path.join(folder_path, img_name)
img.save(img_path, 'JPEG', quality=95)
logger.info(f"已下载并转换为JPG: {img_path}")
return True

View File

@@ -8,8 +8,8 @@ import io
def compress_image(image_path, target_size_kb=300):
"""快速压缩图片到目标大小单位KB"""
img = PILImage.open(image_path)
with PILImage.open(image_path) as img:
# 调整图片尺寸,保持宽高比
# 如果图片有透明度转换为RGB
if img.mode in ('RGBA', 'P'):
img = img.convert('RGB')
@@ -85,7 +85,7 @@ def create_pdf_from_images(directory, output_pdf):
compressed_image_data = compress_image(image_file)
# 从压缩字节数据中读取图片以获取新尺寸
compressed_img = PILImage.open(io.BytesIO(compressed_image_data))
with PILImage.open(io.BytesIO(compressed_image_data)) as compressed_img:
img_width, img_height = compressed_img.size
# 设置目标宽度适应A3页面宽度最大800点

View File

@@ -182,9 +182,8 @@ def fetch_and_create_pdf(url):
if image:
try:
# 使用PIL处理图片尺寸
img = PILImage.open(image)
with PILImage.open(image) as img:
img_width, img_height = img.size
# 计算缩放比例,确保图片适应页面
scale_width = max_image_width / img_width
scale_height = max_image_height / img_height
@@ -201,7 +200,6 @@ def fetch_and_create_pdf(url):
# 添加图片到内容中,使用计算后的尺寸
content.append(Image(img_stream, width=new_width, height=new_height))
content.append(Spacer(1, 4))
print(f"处理图片: 原始尺寸 {img_width}x{img_height}, 新尺寸 {new_width}x{new_height}")
except Exception as e:
print(f"处理图片时出错: {e}")