Bohdan Vorona
Bohdan Vorona

Reputation: 725

Bad image quality converted from PDF file (PHP + Imagick)

My code:

$pdf = $this->name;
$saveAsPath = $this->path;

$img = new \Imagick($pdf);
$img->setResolution(300, 300);
$num_pages = $img->getNumberImages();
$img->setImageCompressionQuality(100);

for ($i = 0; $i < $num_pages; $i++) {
    $img->setIteratorIndex($i);
    $img->setImageFormat('jpeg');
    $img->writeImage($saveAsPath . '/' . $i.'.jpg');
}

$img->destroy();

Results:

Original file:

enter image description here

After Imagick:

enter image description here

As we can see lines and letters are worse. How can I improve the quality?

Upvotes: 1

Views: 3759

Answers (1)

Bohdan Vorona
Bohdan Vorona

Reputation: 725

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

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

So, this is the working solution:

$pdf = $this->name;
$saveAsPath = $this->path;

$img = new \Imagick();
$img->setResolution(300, 300);
$img->readImage($pdf);
$num_pages = $img->getNumberImages();
$img->setImageCompressionQuality(100);

for ($i = 0; $i < $num_pages; $i++) {
    $img->setIteratorIndex($i);
    $img->setImageFormat('jpeg');
    $img->writeImage($saveAsPath . '/' . $i.'.jpg');
}

$img->destroy();

Upvotes: 3

Related Questions