为什么我的缩放图像总是黑色?

时间:2014-06-07 00:05:39

标签: php image-scaling

我正在制作缩略图,出于某种原因,我的输出尺寸正确,但总是黑色。我在类似的主题上看到了另一个Stack Overflow帖子,但在他的情况下,他传递的参数不正确。

我正在从摄像机拍摄图像,然后使用此代码:

$data = base64_decode($data); // the data will be saved to the db

$image = imagecreatefromstring($data); // need to create an image to grab the width and height
$img_width = imagesx($image);
$img_height = imagesy($image);

// calculate thumbnail size
$new_height = 100;
$new_width = floor( $img_width * ( 100 / $img_height ) );

// create a new temporary image
$new_image = imagecreatetruecolor( $new_width, $new_height );

// copy and resize old image into new image
imagecopyresampled( $new_image, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height );
$url = IMGDIR.$imgname;
$thumburl = IMGDIR."thumb/".$imgname;

// save image and thumb to disk
imagepng($image,$url);
imagepng($new_image,$thumburl);

我得到的结果是两个文件都保存到正确的目录,两者都是正确的大小,但缩略图都是黑色的。我必须要有一些简单的东西。有什么想法吗?

2 个答案:

答案 0 :(得分:1)

尝试使用imagesavealpha保存图片的Alpha通道,并为第二个参数传递true

imagesavealpha($image, true);
imagepng($image,$url);

imagesavealpha($new_image, true);
imagepng($new_image,$thumburl);

答案 1 :(得分:1)

请记住,PNG文件具有Alpha通道。因此,请务必使用imagealphablendingimagesavealpha。在这里,它们已集成到您的代码中。

$data = base64_decode($data); // the data will be saved to the db

$image = imagecreatefromstring($data); // need to create an image to grab the width and height
$img_width = imagesx($image);
$img_height = imagesy($image);

// calculate thumbnail size
$new_height = 100;
$new_width = floor( $img_width * ( 100 / $img_height ) );

// create a new temporary image
$new_image = imagecreatetruecolor( $new_width, $new_height );

// copy and resize old image into new image
imagecopyresampled($new_image, $image, 0, 0, 0, 0, $new_width, $new_height, $img_width, $img_height);
$url = IMGDIR . $imgname;
$thumburl = IMGDIR . "thumb/" . $imgname;

// Set the image alpha blending settings.
imagealphablending($image, false);
imagealphablending($new_image, false);

// Set the image save alpha settings.
imagesavealpha($image, true);
imagesavealpha($new_image, true);

// save image and thumb to disk
imagepng($image,$url);
imagepng($new_image,$thumburl);