Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php Imagemagick jpg black background

I have a php script to create jpg thumbnail of pdf as follows;

<?php
$file ="test.pdf";
$im = new imagick(realpath($file).'[0]');
$im->setImageFormat("jpg");
$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)."' />";
?>

But the resulting jpg have black background instead of white.. How can I fix this??

like image 925
Alfred Avatar asked May 23 '11 15:05

Alfred


3 Answers

None of the previously posted answers worked for me however the below did:

$image = new Imagick;

$image->setResolution(300, 300);

$image->readImage("{$originalPath}[0]");

$image->setImageFormat('jpg');

$image->scaleImage(500, 500, true);

$image->setImageAlphaChannel(Imagick::VIRTUALPIXELMETHOD_WHITE);

As I'm using the Laravel framework I then take the converted image and store it using Laravels filesystem.

Storage::put($storePath, $image->getImageBlob());

Update: So I recently changed OS and whereas this previously worked on my Ubuntu machine on my Mac certain images were still coming out black.

I had to change the script to the below:

$image = new Imagick;

$image->setResolution(300, 300);

$image->setBackgroundColor('white');

$image->readImage("{$originalPath}[0]");

$image->setImageFormat('jpg');

$image->scaleImage(500, 500, true);

$image->mergeImageLayers(Imagick::LAYERMETHOD_FLATTEN);

$image->setImageAlphaChannel(Imagick::ALPHACHANNEL_REMOVE);

Seems important to set the background colour before reading in the image. I also flatten any possible layers and remove the alpha channel. I feel like I tried ALPHACHANNEL_REMOVE on my Ubuntu machine and it didn't work so hopefully between these answers readers can find something that works for them.

like image 69
Luke Vincent Avatar answered Sep 28 '22 08:09

Luke Vincent


If your version of Imagick is not up to date, the setImageBackgroundColor may be wrong.

Swap the following line

$im->setImageBackgroundColor("red");

to this (Imagick version >= 2.1.0)

$im->setBackgroundColor(new ImagickPixel("red"));

or (Imagick version < 2.1.0)

$im->setBackgroundColor("red");
like image 31
carlgarner Avatar answered Sep 28 '22 08:09

carlgarner


I solved it by;

$im = new imagick(realpath($file).'[0]');
$im->setCompression(Imagick::COMPRESSION_JPEG);
$im->setCompressionQuality(100);
$im->setImageFormat("jpeg");
$im->writeImage("imagename.jpg");
like image 22
Alfred Avatar answered Sep 28 '22 07:09

Alfred