我正在尝试用PHP帮助将PDF转换为IMG (JPG)。
我正在使用imagick扩展
这是我的代码
$fp_pdf = fopen($pdf, 'rb');
$img = new imagick(); // [0] can be used to set page number
$img->readImageFile($fp_pdf);
$img->setImageFormat( "jpg" );
$img->setImageCompression(imagick::COMPRESSION_JPEG);
$img->setImageCompressionQuality(90);
$img->setResolution(300,300);
$img->setImageUnits(imagick::RESOLUTION_PIXELSPERINCH);
$data = $img->getImageBlob();
我的源pdf文件有正确的尺寸(210x297毫米,像A4有)。一切看起来都很好。但我的jpg页面尺寸为842x595像素,DPI为72。
和img文件在纸上比pdf小得多,当我要打印它的时候。
什么是正确的方法,使图像文件从PDF,并使其如此大的PDF(在纸上)
您可以通过exec()或类似的方法使用imagemagick, shell参数比PHP扩展少得多。
$pdf_file = escapeshellarg( "mysafepdf.pdf" );
$jpg_file = escapeshellarg( "output.jpg" );
$result = 0;
exec( "convert -density 300 {$pdf_file} {$jpg_file}", null, $result );
// at this point $result should == 0 if the conversion was successful
它是"-density"(设置DPI读取源文件为)选项,专门解决您的问题。
在大多数情况下,imagemagick默认使用92的-quality设置来进行JPEG写入,因此您可能不需要显式声明它。
你好像漏掉了两个设置:
Imagick: setImagePage () http://www.php.net/manual/en/function.imagick-setimagepage.php
:
Imagick: setImageExtent () http://www.php.net/manual/en/function.imagick-setimageextent.php
为了获得这些函数的正确参数,您可以尝试以下操作:
$fp_pdf = fopen($pdf, 'rb');
$params=array();
$img = new imagick();
$img->readImageFile($fp_pdf);
/*my modification: */$img->setImageUnits(imagick::RESOLUTION_PIXELSPERINCH);
/*my modification: */$params=$img->identifyImage();
$img->setImageFormat( "jpg" );
$img->setImageCompression(imagick::COMPRESSION_JPEG);
$img->setImageCompressionQuality(90);
/*my modification: */$img->setPage($params['geometry']['width'], $params['geometry']['height'], 0, 0)
/*my modification: */$img->setResolution($params['resolution']['x'], $params['resolution']['y']);
$img->setImageUnits(imagick::RESOLUTION_PIXELSPERINCH);
$data = $img->getImageBlob();
如果您发现需要设置一些其他属性,那么让我向您展示$params保存的信息。它可能对你有用:
$params=array(
[imageName],
[format],
[geometry] => Array
(
[width]
[height]
)
[type],
[colorSpace],
[resolution],
(
[x]
[y]
)
[units],
[fileSize],
[compression],
[signature],
)
老实说,我不完全确定这是否有效。只是为了帮助你而尝试。
ImageMagick使用GhostScript来处理jpeg,所以你最好直接使用exec
GhostScript,这将更有效,并给你更多的控制。它也将只有一个exec
语句,而不是玩弄IMagick函数。
如前所述,在读取文件之前设置分辨率是可行的:
$fp_pdf = fopen($pdf, 'rb');
$img = new imagick(); // [0] can be used to set page number
$img->setResolution(300,300);
$img->readImageFile($fp_pdf);
$img->setImageFormat( "jpg" );
$img->setImageCompression(imagick::COMPRESSION_JPEG);
$img->setImageCompressionQuality(90);
$img->setImageUnits(imagick::RESOLUTION_PIXELSPERINCH);
$data = $img->getImageBlob();
您必须在读取图像之前调用setResolution。否则imagemagick将使用默认的系统dpi