为什么我在PHP中用GD自动生成的缩略图都有黑色背景?

时间:2009-05-18 20:34:05

标签: php gd thumbnails

我正在使用以下代码将任何旧图像转换为160x120缩略图,问题是如果有溢出,则背景始终为黑色。我一直在窥探PHP文档,但这些函数似乎都没有任何颜色参数。任何想法或指示都会很棒!

$original = 'original_image.jpg';
$thumbnail = 'output_thumbnail.jpg';

list($width,$height) = getimagesize($original);
$width_ratio = 160 / $width;
if ($height * $width_ratio <= 120)
{
    $adjusted_width = 160;
    $adjusted_height = $height * $width_ratio;
}
else
{
    $height_ratio = 120 / $height;
    $adjusted_width = $width * $height_ratio;
    $adjusted_height = 120;
}
$image_p = imagecreatetruecolor(160,120);
$image = imagecreatefromjpeg($original);
imagecopyresampled($image_p,$image,ceil((160 - $adjusted_width) / 2),ceil((120 - $adjusted_height) / 2),0,0,ceil($adjusted_width),ceil($adjusted_height),$width,$height);
imagejpeg($image_p,$thumbnail,100);

另外,如果您不清楚我的意思,请this image并认为它原本只是白色背景上的红色文字

3 个答案:

答案 0 :(得分:2)

imagecreatetruecolor function会创建一个黑色画布。

使用imagefill功能将其绘制为白色......

答案 1 :(得分:1)

在将原件复制到新版本之前添加它:

$white = ImageColorAllocate($image_p, 255, 255, 255); 
ImageFillToBorder($image_p, 0, 0, $white, $white);

编辑:

实际上,我不知道imagefill。 。

$white = imagecolorallocate($image_p, 255, 255, 255); 
imagefill($image_p, 0, 0, $white);

答案 2 :(得分:0)

不要使用imagecreatetruecolor而不是imagecreate,我认为这样可以解决

相关问题