set density parameter for imagick with php
Asked Answered
G

2

8

I want to convert a pdf page to a png image with Imagick.

I tried with PHP, but the image quality was very low.
When I tried with command line, the result was perfect.

PHP code

$im = new imagick( __DIR__ . DIRECTORY_SEPARATOR.$PDFName.'['.$i.']' );  
$params = $im->identifyImage();
$width = $params['geometry']['width']*1;
$height = $params['geometry']['height']*1;
$im->setResolution(400,400);
$im->resizeImage($width ,$height, imagick::FILTER_SINC, 1, true);
$im->writeImage(__DIR__ . DIRECTORY_SEPARATOR.'pdf_pages\\'.$i.'.png'); 
$im->clear(); 
$im->destroy();

Command line code

convert -density 400 a.pdf -resize 25% -a.png

PHP code (2nd attempt)

$im = new imagick( __DIR__ . DIRECTORY_SEPARATOR.$PDFName.'['.$i.']' );  
$im->setOption('density','400x400');
$im->setOption('resize','25%');
$im->writeImage(__DIR__ . DIRECTORY_SEPARATOR.'pdf_pages\\'.$i.'.png'); 
$im->clear(); 
$im->destroy();

Still bad results.

What can I do? I want to use the density parameter in my PHP code, but how?

Output with PHP enter image description here

Output with command line enter image description here

Gibran answered 25/12, 2012 at 20:58 Comment(3)
You should provide the PDF file as well.Kiangsi
Here is PDF file => cevhersys.net/5663.pdfGibran
Also, if the PHP API fails to get you what you need, you can always resort back to using exec or shell_exec to execute the command and generate the file you need.Runkle
G
30

You need to set Resolution before you read the file.

$im = new imagick();
$im->setResolution(200,200);
$im->readImage(__DIR__ . DIRECTORY_SEPARATOR.$PDFName.'['.$i.']');

Than, the result will be perfect.

Hope this help someone.

Goodyear answered 29/8, 2013 at 21:34 Comment(0)
R
5

From the manual http://php.net/manual/en/imagick.setresolution.php

Imagick::setResolution() must be called before loading or creating an image.

See this answer Pdf to image using php-imagick api

Runkle answered 26/12, 2012 at 2:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.