PHP 缩略图问题,缩略后怎么成了黑色的图片,求解答 急急急

![图片说明](https://img-ask.csdn.net/upload/201705/04/1493870341_442730.png)图片说明

<?
header("Content-type: image/jpeg");

//创建并载入一幅图像
$im = @imagecreatefromjpeg("images/flower_1.jpg");

//错误处理
if(!$im){
$im = imagecreatetruecolor(150, 30);
$bg = imagecolorallocate($im, 255, 255, 255);
$text_color = imagecolorallocate($im, 0, 0, 255);
//填充背景色
imagefilledrectangle($im, 0, 0, 150, 30, $bg);
//以图像方式输出错误信息
imagestring($im, 3, 5, 5, "Error loading image", $text_color);
} else {
//输出该图像
imagejpeg($im);
}
?>

调色板图像色彩数量限制为256色,而图像重新采样(Resampling)的操作需要色彩数量通常大于256。
对于不在此范围内的像素颜色,会尝试赋一个近似值,很大概率就会导致如题目中描述的现象。

  解决办法是需要用imagecreatetruecolor()函数创建新图。

附上一个例程,如下代码将原图缩小为1/2:

<?php
// The file
$filename = 'test.jpg';
$percent = 0.5;

// Content type
header('Content-Type: image/jpeg');

// Get new dimensions
list($width, $height) = getimagesize($filename);
$new_width = $width * $percent;
$new_height = $height * $percent;

// Resample
$image_p = imagecreatetruecolor($new_width, $new_height);
$image = imagecreatefromjpeg($filename);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);

// Output
imagejpeg($image_p, null, 100);
?>

第一个gd对象没有调色。