4

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?

halfer
  • 19,824
  • 17
  • 99
  • 186
Alfred
  • 21,058
  • 61
  • 167
  • 249
  • If you make it to be a jpg file instead of a png? – George Kastrinis May 23 '11 at 14:49
  • I agree, see http://stackoverflow.com/questions/2569970/gd-converting-a-png-image-to-jpeg-and-making-the-alpha-by-default-white-and-not – AllisonC May 23 '11 at 14:54
  • initially i tried to make jpg file... but i got a jpg with black background `:P` `:P` .. thats y i turned to png... do u know how to change jpg black background color?? or suggest me how to set one in png... – Alfred May 23 '11 at 14:56
  • @AllisonC, I want to do it without GD. I first tried to make a jpg, but got one with black background. Do u know how to fix dat?? – Alfred May 23 '11 at 15:05
  • i would try to draw a rectangle, same size as the image and fill it ... ? – helle May 23 '11 at 16:33
  • @helle, that's tough... any way.. best of luck.. :) – Alfred May 23 '11 at 16:37
  • I don't get it. I am no native english speaker. what means ny? what means bast? thanks – helle May 23 '11 at 16:39

2 Answers2

4

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);
Alessandro Minoccheri
  • 35,521
  • 22
  • 122
  • 171
TheTambu
  • 121
  • 1
  • 4
2

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)."' />";    
?>
TeckniX
  • 673
  • 1
  • 7
  • 14