Skip to content

Commit

Permalink
Merge pull request PrestaShop#35603 from jf-viguier/png-8bits
Browse files Browse the repository at this point in the history
Support 8 bits PNG file
  • Loading branch information
nicosomb authored Jul 4, 2024
2 parents 0899c72 + 6793d47 commit 67aa2da
Showing 1 changed file with 23 additions and 2 deletions.
25 changes: 23 additions & 2 deletions classes/ImageManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -307,8 +307,13 @@ public static function resize(
$destImage = imagecreatetruecolor($destinationWidth, $destinationHeight);

// If the output is PNG, fill with transparency. Else fill with white background.
if ($destinationFileType == 'png' || $destinationFileType == 'webp' || $destinationFileType == 'avif') {
imagealphablending($destImage, false);
if (in_array($destinationFileType, ['png', 'webp', 'avif'])) {
// if png color type is 3, the file is paletted (256 colors or less). Change palette to reduce file size
if ($destinationFileType == 'png' && $sourceFileType == IMAGETYPE_PNG && self::getPNGColorType($sourceFile) == 3) {
imagetruecolortopalette($destImage, false, 255);
} else {
imagealphablending($destImage, false);
}
imagesavealpha($destImage, true);
$transparent = imagecolorallocatealpha($destImage, 255, 255, 255, 127);
imagefilledrectangle($destImage, 0, 0, $destinationWidth, $destinationHeight, $transparent);
Expand Down Expand Up @@ -896,4 +901,20 @@ public static function get_best_path($tgt_width, $tgt_height, $path_infos)

return $path;
}

/**
* The function `getPNGColorType` returns the color type byte from a PNG file
*
* @param string $fileName
*
* @return int|bool
*/
public static function getPNGColorType($fileName)
{
if (!is_readable($fileName)) {
return false;
}

return ord(@file_get_contents($fileName, false, null, 25, 1));
}
}

0 comments on commit 67aa2da

Please sign in to comment.