使用PHP ImageMagick库将pdf文件的前n页转换为单个png图像文件



我正在使用PHP ImageMagick库将上传的pdf文件转换为单个png文件,以便我可以将pdf作为单个图像显示在我的Laravel网页上。到目前为止,我能够用以下代码将整个pdf转换为单个图像:

<?php
$imagick = new Imagick();
$file = new File;
// other lines of code
// ...
$imgPath = Storage::path($file->file_path);
$imgSavePath = Storage::path('uploads/buffer/'.Str::beforeLast($file->name, '.').'.png');
$imagick->readImage($imgPath);
$imagick->resetIterator();
$imagick = $imagick->appendImages(true);
$imagick->writeImages($imgSavePath, true);

这通过生成单个png图像来工作。然而,我发现这是资源密集型(存储方面)和耗时的,因为我是通过ajax调用交付功能的。

我希望我的web应用程序只转换pdf的第一个n页(说前5页)成一个图像作为网站上的预览-此后用户可以下载整个pdf在他们的本地系统上查看。无论上传的pdf文档有多少页,该函数都应该可以工作。

到目前为止,我只在文档中找到了可以从Imagick对象读取特定索引处的页面并使用 转换为图像的地方:
...
$imgPath = Storage::path($file->file_path);
$index = 5;
$imagick->readImage($imgPath. '[' . $index . ']');

然而,我发现很难重构它,以便应用程序可以读取第一个n页。

直观地看,readImage()函数的工作方式似乎与命令行语法类似。感谢@MarkSetchell在评论中的提示:

<?php
$imagick = new Imagick();
$file = new File;
// other lines of code
// ...
$imgPath = Storage::path($file->file_path);
$imgSavePath = Storage::path('uploads/buffer/'.Str::beforeLast($file->name, '.').'.png');
$imagick->readImage($imgPath.'[0-4]'); // read only the first 5 pages
$imagick->resetIterator();
$imagick = $imagick->appendImages(true);
$imagick->writeImages($imgSavePath, true); 

我使用ImageMagick 6.9.10-68PHP 8.1.12

最新更新