Reputation: 21386
I have a PHP script to create a PNG thumbnail of a PDF file as follows:
<?php
$file ="test.pdf";
$im = new imagick(realpath($file).'[0]');
$im->setImageFormat("png");
$im->resizeImage(200,200,1,0);
// start buffering
ob_start();
$thumbnail = $im->getImageBlob();
$contents = ob_get_contents();
ob_end_clean();
echo "<img src='data:image/jpg;base64,".base64_encode($thumbnail)."' />";
?>
Which returns a thumbnail, but the background is transparent. I want to set white background color (change the alpha layer to white). How can I do this?
Upvotes: 4
Views: 4947
Reputation: 131
The solution is not in the background colour, but in the alpha channel! Try with this code:
$im->readImage($fileInput);
$im->setImageAlphaChannel(imagick::ALPHACHANNEL_DEACTIVATE);
Upvotes: 5
Reputation: 673
I'm doing something similar, although I'm actually writing the image to the disk - When I used your direct output, it worked and I got the actual color from the PDF.
Through a bit of debugging, I figured that the issue was actually related to the
imagick::resizeImage()
function. For whatever reason, when you set all of your colors, compression, etc. the resizeImage adds the black background. My solution is to use GD for the resizing, so that I can have a full dynamic resize - Since you're not interested in such thing, I would simply use the image sampling functionality. Your code should be like this:
<?php
$file ="test.pdf";
$im = new imagick(realpath($file).'[0]');
$im->setCompression(Imagick::COMPRESSION_JPEG);
$im->setCompressionQuality(80);
$im->setImageFormat("jpeg");
$im->sampleImage(200,200);
// start buffering
ob_start();
$thumbnail = $im->getImageBlob();
$contents = ob_get_contents();
ob_end_clean();
echo "<img src='data:image/jpg;base64,".base64_encode($thumbnail)."' />";
?>
Upvotes: 2