Set the background color of the image imagemagick png

I have a php script to create a thumbnail png 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)."' />"; ?> 

Returns a sketch, but the background is transparent. I want to set the background color to white (change the alpha layer to white). How can i do this?

Thanks in advance ... :)

blasteralfred

+4
source share
2 answers

I do something similar, although I actually write the image to disk - When I used your direct output, it worked, and I got the actual color from the PDF.

After a bit of debugging, I realized that the problem was related to

 imagick::resizeImage() 

function. For some reason, when you set all your colors, compression, etc., ResizeImage adds a black background. My solution is to use GD to resize so that I have full dynamic size. Since you are not interested in this, I would simply use the image selection function. Your code should look 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)."' />"; ?> 
+2
source

The solution is not in the background color, but in the alpha channel! Try using this code:

 $im->readImage($fileInput); $im->setImageAlphaChannel(imagick::ALPHACHANNEL_DEACTIVATE); 
+3
source

All Articles