繁体   English   中英

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

[英]Convert the first n pages of a pdf file to a single png Image file using PHP ImageMagick library

我正在使用PHP ImageMagick 库将上传的 pdf 文件转换为单个 png 文件,这样我就可以在我的 Laravel 网页上将 pdf 作为单个图像显示。 到目前为止,我可以使用以下代码将整个 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 文档中的页数如何,function 都应该有效。

到目前为止,我只在文档中找到我可以从 Imagick object 读取特定索引处的页面并使用以下方法转换为图像:

...
$imgPath = Storage::path($file->file_path);
$index = 5;
$imagick->readImage($imgPath. '[' . $index . ']');

但是,我发现很难重构它以便应用程序可以读取前n页。

直观上, readImage() function 似乎以与命令行语法类似的方式工作。 感谢@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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM