PHP使用Imagick库操作tiff
1. 获取tiff页数
function page_count($tiffPath): int
{$image = new \Imagick($tiffPath);// 获取TIFF文件中的页数$pages = $image->getNumberImages();// 释放内存$image->clear();return (int) $pages;
}
2. 拆分tiff页面为jpeg
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
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"