使用Imagick将每个PDF页面保存到图像 [英] Saving Each PDF Page to an Image Using Imagick
问题描述
我在下面有以下php函数将本地PDF文件转换为图像。简而言之,我希望每个PDF页面都转换为单独的图像。
I have the following php function below that's converting a local PDF file into images. In short, I want each PDF page to be converted to a separate image.
该函数将PDF转换为图像 - 但仅限于最后一页。我希望将 PDF的每个 页面转换为图像并进行编号。不仅仅是PDF的最后一页。
The function converts the PDF to an image - but only the last page. I want every page of the PDF to be converted to a image and numbered. Not just the last page of the PDF.
目前,此功能可转换<$ c的 last 页面$ c> example.pdf 到 example-0.jpg
。问题我确定在中的
方法。我缺少什么?
Currently, this function converts the last page of example.pdf
to example-0.jpg
. Issue I'm sure lies within the for
method. What am I missing?
$file_name = 'example.pdf'; // using just for this example, I pull $file_name from another function
function _create_preview_images($file_name) {
// Strip document extension
$file_name = basename($file_name, '.pdf');
// Convert this document
// Each page to single image
$img = new imagick('uploads/'.$file_name.'.pdf');
// Set background color and flatten
// Prevents black background on objects with transparency
$img->setImageBackgroundColor('white');
$img = $img->flattenImages();
// Set image resolution
// Determine num of pages
$img->setResolution(300,300);
$num_pages = $img->getNumberImages();
// Compress Image Quality
$img->setImageCompressionQuality(100);
// Convert PDF pages to images
for($i = 0;$i < $num_pages; $i++) {
// Set iterator postion
$img->setIteratorIndex($i);
// Set image format
$img->setImageFormat('jpeg');
// Write Images to temp 'upload' folder
$img->writeImage('uploads/'.$file_name.'-'.$i.'.jpg');
}
$img->destroy();
}
推荐答案
似乎 <我的代码中的大多数 是正确的。问题是,我正在使用 $ img-> flattenImages();
错误。此将
一系列图像合并为一个图像。就像Photoshop在导出 jpg
时将所有可见图层展平成图像一样。
Seems like most of my code was correct. The issue was, I was using $img->flattenImages();
incorrectly. This merges
a sequence of images into one image. Much like how Photoshop flattens all visible layers into an image when exporting a jpg
.
我删除了上面的行并且单个文件按预期编写。
I removed the above line and the individual files were written as expected.
这篇关于使用Imagick将每个PDF页面保存到图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!