Можно добавить цвет фона к прозрачному изображению с помощью GD и PHP

У меня есть класс создания миниатюр, написанный с использованием php-языка с использованием GD. Я хочу знать, когда я загружаю прозрачное изображение, которое является png или gif, могу ли я установить фон в этом миниатюрном изображении? Если это возможно, пожалуйста, любезно посоветуйте мне, как это сделать. Благодарю.

Solutions Collecting From Web of "Можно добавить цвет фона к прозрачному изображению с помощью GD и PHP"

Вот работающее решение для файлов PNG:

$filePath = ''; //full path to your png, including filename and extension $savePath = ''; //full path to saved png, including filename and extension $colorRgb = array('red' => 255, 'green' => 0, 'blue' => 0); //background color $img = @imagecreatefrompng($filePath); $width = imagesx($img); $height = imagesy($img); //create new image and fill with background color $backgroundImg = @imagecreatetruecolor($width, $height); $color = imagecolorallocate($backgroundImg, $colorRgb['red'], $colorRgb['green'], $colorRgb['blue']); imagefill($backgroundImg, 0, 0, $color); //copy original image to background imagecopy($backgroundImg, $img, 0, 0, 0, 0, $width, $height); //save as png imagepng($backgroundImg, $savePath, 0); 

Почему нет:

  1. Создайте изображение с желаемым фоном
  2. Нарисуйте над ним прозрачное изображение
  3. Сохраните новое изображение поверх прозрачного.

Очень простой код с динамическим цветом фона.

 <?php function hex2RGB($hexStr, $retur`enter code here`nAsString = false, $seperator = ',') { $hexStr = preg_replace("/[^0-9A-Fa-f]/", '', $hexStr); // Gets a proper hex string $rgbArray = array(); if (strlen($hexStr) == 6) { //If a proper hex code, convert using bitwise operation. No overhead... faster`enter code here` $colorVal = hexdec($hexStr); $rgbArray['red'] = 0xFF & ($colorVal >> 0x10);`enter code here` $rgbArray['green'] = 0xFF & ($colorVal >> 0x8); $rgbArray['blue'] = 0xFF & $colorVal; } elseif (strlen($hexStr) == 3) { //if shorthand notation, need some string manipulations $rgbArray['red'] = hexdec(str_repeat(substr($hexStr, 0, 1), 2)); $rgbArray['green'] = hexdec(str_repeat(substr($hexStr, 1, 1), 2)); $rgbArray['blue'] = hexdec(str_repeat(substr($hexStr, 2, 1), 2)); } else { return false; //Invalid hex color code } return $returnAsString ? implode($seperator, $rgbArray) : $rgbArray;die; } $color_code = hex2RGB('#fff000'); $imgName = uniqid(); $filePath = 'old-img/clothing_type_test.png'; //full path to your png, including filename and extension $savePath = 'new-img/'.$imgName.'.png'; //full path to saved png, including filename and extension $colorRgb = array('red' => $color_code['red'], 'green' => $color_code['green'], 'blue' => $color_code['blue']); //background color $img = @imagecreatefrompng($filePath); $width = imagesx($img); $height = imagesy($img); $backgroundImg = @imagecreatetruecolor($width, $height); $color = imagecolorallocate($backgroundImg, $colorRgb['red'], $colorRgb['green'], $colorRgb['blue']); imagefill($backgroundImg, 0, 0, $color); imagecopy($backgroundImg, $img, 0, 0, 0, 0, $width, $height); imagepng($backgroundImg, $savePath, 0); ?> <p align="center"><img align="absmiddle" src="<?php echo $savePath;?>" /></p>