我有使用 GD 的 php 语言编写的缩略图创建类。我想知道当我上传透明图像是 png 或 gif 时,我可以把背景放在那个缩略图中吗?如果可能的话,请指导我如何。谢谢。
Isaveit
问问题
11465 次
3 回答
10
这是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);
于 2011-12-09T15:14:24.757 回答
1
为什么不:
- 创建具有所需背景的图像
- 在其上方绘制透明图像
- 将新图像保存在透明图像上。
于 2009-09-30T11:49:24.187 回答
1
具有动态背景颜色的非常简单的代码。
<?php
function hex2RGB($hexStr, $returnAsString = 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
$colorVal = hexdec($hexStr);
$rgbArray['red'] = 0xFF & ($colorVal >> 0x10);
$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>
于 2014-01-03T06:14:49.047 回答