Doug Wolfgram
Doug Wolfgram

Reputation: 2126

Why is my scaled image always black?

I am making thumbnails and for some reason, my output is the correct size, but always black. I saw another Stack Overflow post on a similar topic but in his case, he was passing parameters incorrectly.

I am capturing an image from a video camera and then using this code:

$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);

The result I get is both files saved to the proper directories, both the proper size, but the thumbnail is all black. There must be something simple I am missing. Any ideas?

Upvotes: 0

Views: 148

Answers (2)

Giacomo1968
Giacomo1968

Reputation: 26066

Remember that PNG files have alpha channels. So be sure to use imagealphablending and imagesavealpha. Here they are integrated into your code.

$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);

Upvotes: 1

FuzzyTree
FuzzyTree

Reputation: 32392

Try saving your image's alpha channel with imagesavealpha and passing true for the 2nd argument

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

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

Upvotes: 1

Related Questions