Php Imagemagick jpg black background

I have a php script to create a JPG thumbnail in pdf format 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 as a result of jpg there is a black background instead of white. How can i fix this?

+5
source share
5 answers

I solved it:

$im = new imagick(realpath($file).'[0]');
$im->setCompression(Imagick::COMPRESSION_JPEG);
$im->setCompressionQuality(100);
$im->setImageFormat("jpeg");
$im->writeImage("imagename.jpg");
+1
source

If your version of Imagick is not updated, a setImageBackgroundColor error may occur.

Toggle next 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");
+1
source

JPG

-alpha off
+1

$im->setimageformat("jpg"); $im->setimageformat("png");, .

+1

, :

$image = new Imagick;

$image->setResolution(300, 300);

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

$image->setImageFormat('jpg');

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

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

Laravel, Laravels.

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

Update: so I changed OS recently, and although it previously worked on my Ubuntu machine on my Mac, some images still came out of black.

I had to change the script to 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);

It seems important to set the background color before reading on the image. I also smooth out any possible layers and delete the alpha channel. I feel like I tried ALPHACHANNEL_REMOVEon my Ubuntu machine and it didn’t work so reliably between these answers, readers may find something that works for them.

+1
source

All Articles