Categories
Imagick PHP Programming

Convert white in image to transparency with Imagick and PHP

Here is a snippet I made which takes a path to an image and if the image doesn’t have any transparency it replaces all white color with 100% transparency.

[code lang=”php”]
/**
* @static
* @param string $oldPath
* @param string|null [$newPath = null]
* @throws \Exception
* @return bool
*/
public static function createShirtImage($oldPath, $newPath = null)
{
if (isset($oldPath)
&& file_exists($oldPath)
) {

if ($resource = new imagick($oldPath)) {

$whitePixel = new ImagickPixel(‘white’);

// Does image not have any transparency?
if (!$resource->getimagealphachannel()) {

$resource->painttransparentimage(
$whitePixel,
0.0,
5000
);

}

$resource->setimagecolorspace(imagick::COLORSPACE_RGB);
$resource->setimageformat(‘png’);

if (empty($newPath)) {
$newPath = $oldPath;
}

if (file_exists($newPath)) {
unlink($newPath);
}

if ($resource->writeimage($newPath)) {

return true;

}

}

} else {
Throw new Exception(‘Invalid parameters’);
}

return false;

}
[/code]

Leave a Reply