PHP使用Imagick库操作tiff

1. 获取tiff页数

php 复制代码
function page_count($tiffPath): int
{
    $image = new \Imagick($tiffPath);
    // 获取TIFF文件中的页数
    $pages = $image->getNumberImages();
    // 释放内存
    $image->clear();
    return (int) $pages;
}

2. 拆分tiff页面为jpeg

php 复制代码
function extract($tiffPath, int $quality = 90, string $savePath = ''): array
{
    if (empty($savePath)) {
        $savePath = dirname($tiffPath) . DIRECTORY_SEPARATOR . pathinfo($tiffPath, PATHINFO_FILENAME);
    }
    if (! is_dir($savePath)) {
        mkdir($savePath, 0777, true);
    }
    // 创建Imagick对象
    $image = new \Imagick($tiffPath);

    // 获取TIFF文件中的页数
    $pages = $image->getNumberImages();
    $res   = [];
    for ($i = 0; $i < $pages; $i++) {
        // 分离每一页
        $image->setIteratorIndex($i);
        $page = $image->getImage();

        // 设置JPEG格式和质量
        $page->setImageFormat('jpeg');
        $page->setImageCompressionQuality($quality);

        // 生成输出文件名
        $outputFile = $savePath . DIRECTORY_SEPARATOR . ($i + 1) . '.jpg';

        // 保存JPEG文件
        $page->writeImage($outputFile);

        // 释放内存
        $page->clear();
        $res[] = $outputFile;
    }

    // 释放内存
    $image->clear();
    return $res;
}

3. tiff转pdf

php 复制代码
function to_pdf($tiffPath, string $pdfPath = '', bool $force = false): bool
{
    if (is_file($pdfPath) && ! $force) {
        return true;
    }
    if (empty($pdfPath)) {
        $pdfPath = $tiffPath . '.pdf';
    }
    $imagick = new \Imagick();

    // 分页读取
    $imagick->readImage($tiffPath);

    // 逐页处理
    $imagick->setIteratorIndex(0);
    $pdf = new Imagick();

    do {
        $page = $imagick->getImage();
        $page->setImageFormat('pdf');
        $pdf->addImage($page);
        $page->clear();
    } while ($imagick->nextImage());

    $pdf->writeImages($pdfPath, true);
    $pdf->clear();
    $imagick->clear();

    return file_exists($pdfPath);
}

唉 不过这个方案有个硬伤,针对大文件会爆内存,也只能对付一下小文件了

因此在此记录一下,然后我要在项目里清理掉这些代码了,因为我用python来实现了相应的处理,然后php通过api进行调用了, 本来信心满满的用rust也写了一个tiff转pdf,可能是俺的rust水平太菜,费了我3天时间,虽然最后搞出来了,打包exe也才5MB,但是耗时并没有缩短,还不如python的方案, 唉 白费了我3天, 真的是用生命诠释了"人生苦短 请用python"

相关推荐
BingoGo1 天前
当你的 PHP 应用的 API 没有限流时会发生什么?
后端·php
JaguarJack1 天前
当你的 PHP 应用的 API 没有限流时会发生什么?
后端·php·服务端
BingoGo2 天前
OpenSwoole 26.2.0 发布:支持 PHP 8.5、io_uring 后端及协程调试改进
后端·php
JaguarJack2 天前
OpenSwoole 26.2.0 发布:支持 PHP 8.5、io_uring 后端及协程调试改进
后端·php·服务端
JaguarJack3 天前
推荐 PHP 属性(Attributes) 简洁读取 API 扩展包
后端·php·服务端
BingoGo3 天前
推荐 PHP 属性(Attributes) 简洁读取 API 扩展包
php
JaguarJack4 天前
告别 Laravel 缓慢的 Blade!Livewire Blaze 来了,为你的 Laravel 性能提速
后端·php·laravel
郑州光合科技余经理5 天前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php
feifeigo1235 天前
matlab画图工具
开发语言·matlab
dustcell.5 天前
haproxy七层代理
java·开发语言·前端