pdf_image_tools.py 1.42 KB
Newer Older
赵小蒙's avatar
赵小蒙 committed
1
2
from loguru import logger

赵小蒙's avatar
赵小蒙 committed
3
from magic_pdf.io.AbsReaderWriter import AbsReaderWriter
赵小蒙's avatar
赵小蒙 committed
4
from magic_pdf.libs.commons import fitz
5
from magic_pdf.libs.commons import join_path
6
from magic_pdf.libs.hash_utils import compute_sha256
赵小蒙's avatar
赵小蒙 committed
7
8


赵小蒙's avatar
赵小蒙 committed
9
def cut_image(bbox: tuple, page_num: int, page: fitz.Page, return_path, imageWriter: AbsReaderWriter):
赵小蒙's avatar
赵小蒙 committed
10
11
12
13
14
    """
    从第page_num页的page中,根据bbox进行裁剪出一张jpg图片,返回图片路径
    save_path:需要同时支持s3和本地, 图片存放在save_path下,文件名是: {page_num}_{bbox[0]}_{bbox[1]}_{bbox[2]}_{bbox[3]}.jpg , bbox内数字取整。
    """
    # 拼接文件名
15
    filename = f"{page_num}_{int(bbox[0])}_{int(bbox[1])}_{int(bbox[2])}_{int(bbox[3])}"
16
17

    # 老版本返回不带bucket的路径
18
    img_path = join_path(return_path, filename) if return_path is not None else None
赵小蒙's avatar
赵小蒙 committed
19

20
21
    # 新版本生成平铺路径
    img_hash256_path = f"{compute_sha256(img_path)}.jpg"
赵小蒙's avatar
赵小蒙 committed
22

赵小蒙's avatar
赵小蒙 committed
23
24
25
26
    if any([bbox[0] >= bbox[2], bbox[1] >= bbox[3]]):
        logger.warning(f"image_bboxes: 错误的box, {bbox}")
        return img_hash256_path

27
28
29
30
31
32
    # 将坐标转换为fitz.Rect对象
    rect = fitz.Rect(*bbox)
    # 配置缩放倍数为3倍
    zoom = fitz.Matrix(3, 3)
    # 截取图片
    pix = page.get_pixmap(clip=rect, matrix=zoom)
赵小蒙's avatar
赵小蒙 committed
33

34
    byte_data = pix.tobytes(output='jpeg', jpg_quality=95)
35

赵小蒙's avatar
赵小蒙 committed
36
    imageWriter.write(byte_data, img_hash256_path, AbsReaderWriter.MODE_BIN)
37

38
    return img_hash256_path