跳转至

批量处理图片

本页面介绍如何批量处理和插入图片。

批量插入

循环插入

from symphra_excel import Workbook
from symphra_excel.images import ExcelImage

with Workbook() as wb:
    sheet = wb.create_worksheet("图片列表")

    image_paths = [
        "image1.png",
        "image2.png",
        "image3.png",
    ]

    for idx, path in enumerate(image_paths, start=1):
        image = ExcelImage(path, width=100, height=100)
        sheet.insert_image(f"A{idx*10}", image)

    wb.save("batch_images.xlsx")

批量优化

批量压缩

from symphra_excel.images import ImageProcessor

processor = ImageProcessor()

images = ["photo1.jpg", "photo2.jpg", "photo3.jpg"]
optimized = []

for img in images:
    compressed = processor.compress(img, quality=80)
    optimized.append(compressed)

完整示例

示例: 产品目录生成

from symphra_excel import Workbook
from symphra_excel.images import ExcelImage, ImageProcessor
from symphra_excel.styles import CellStyle, PredefinedStyles

products = [
    {"name": "产品A", "image": "products/a.jpg", "price": 100},
    {"name": "产品B", "image": "products/b.jpg", "price": 200},
    {"name": "产品C", "image": "products/c.jpg", "price": 300},
]

processor = ImageProcessor()

with Workbook() as wb:
    sheet = wb.create_worksheet("产品目录")

    sheet.set_cell_value("A1", "产品目录")
    sheet.apply_style("A1", PredefinedStyles.title_style())

    row = 3
    for product in products:
        optimized = processor.resize(
            product["image"],
            width=200,
            height=200
        )

        image = ExcelImage(optimized)
        sheet.insert_image(f"A{row}", image)

        sheet.set_cell_value(f"B{row}", product["name"])
        sheet.apply_style(f"B{row}", PredefinedStyles.header_style())

        sheet.set_cell_value(f"B{row+1}", f{product['price']}")
        sheet.apply_style(f"B{row+1}", PredefinedStyles.currency_style())

        row += 15

    wb.save("product_catalog.xlsx")

并发处理

异步批量处理

import asyncio
from symphra_excel.images import ImageProcessor

async def process_images(image_paths):
    processor = ImageProcessor()
    tasks = []

    for path in image_paths:
        task = asyncio.create_task(
            processor.compress_async(path, quality=80)
        )
        tasks.append(task)

    return await asyncio.gather(*tasks)

images = ["img1.jpg", "img2.jpg", "img3.jpg"]
optimized = asyncio.run(process_images(images))

最佳实践

✅ 推荐做法

processor = ImageProcessor()

for img in images:
    optimized = processor.compress(img, quality=80)
    resized = processor.resize(optimized, width=400, height=300)

batch_size = 10
for i in range(0, len(images), batch_size):
    batch = images[i:i+batch_size]

❌ 避免的做法

for img in range(100000):
    image = ExcelImage(f"image_{img}.jpg")
    sheet.insert_image(f"A{img}", image)

下一步