webp invoice creation fix for black background for transparency

Started by Kuubs, December 04, 2025, 10:31:24 AM

Previous topic - Next topic

Kuubs

I fixed a bug in the TCPDF image generation when a webp image is used for the images. At this code at line 7127:

//First use of image, get info
$type = strtolower($type);
if ($type == '') {
$type = TCPDF_IMAGES::getImageFileType($file, $imsize);
} elseif ($type == 'jpg') {
$type = 'jpeg';
}

I added this below:

if ($type === 'webp') {
$webp_tmp = K_PATH_CACHE . '__tcpdf_' . $this->file_id . '_webp2png_' . md5($file);

if (!is_file($webp_tmp)) {
// Prefer GD if it supports WebP
if (function_exists('imagecreatefromwebp')) {
$src = @imagecreatefromwebp($file);
if ($src) {
$wpx = imagesx($src);
$hpx = imagesy($src);

// Create truecolor target with alpha
$dst = imagecreatetruecolor($wpx, $hpx);
imagealphablending($dst, false);
imagesavealpha($dst, true);

// Fully transparent background
$transparent = imagecolorallocatealpha($dst, 255, 255, 255, 127);
imagefill($dst, 0, 0, $transparent);

// Copy original WebP onto transparent canvas
imagecopy($dst, $src, 0, 0, 0, 0, $wpx, $hpx);

// Save as PNG (with alpha)
imagepng($dst, $webp_tmp);

imagedestroy($dst);
imagedestroy($src);
}
}

// Fallback: use Imagick if available
if (!is_file($webp_tmp) && extension_loaded('imagick')) {
try {
$img = new Imagick();
$img->readImage($file);
// keep alpha, just change container format
$img->setImageFormat('png');
$img->writeImage($webp_tmp);
$img->destroy();
} catch (Exception $e) {
// If conversion fails, silently fall back to original behavior
}
}
}

if (is_file($webp_tmp)) {
$file   = $webp_tmp;
$type   = 'png';
$imsize = @getimagesize($file);
}
}

And thus the background is transparent and not black anymore.