imagecreatefrompng() Makes a black background instead of transparent? imagecreatefrompng() Makes a black background instead of transparent? php php

imagecreatefrompng() Makes a black background instead of transparent?


After imagecreatetruecolor():

<?php// ... Before imagecreatetruecolor()$dimg = imagecreatetruecolor($width_new, $height_new); // png ?: gif// start changesswitch ($stype) {    case 'gif':    case 'png':        // integer representation of the color black (rgb: 0,0,0)        $background = imagecolorallocate($dimg , 0, 0, 0);        // removing the black from the placeholder        imagecolortransparent($dimg, $background);        // turning off alpha blending (to ensure alpha channel information        // is preserved, rather than removed (blending with the rest of the        // image in the form of black))        imagealphablending($dimg, false);        // turning on alpha channel information saving (to ensure the full range        // of transparency is preserved)        imagesavealpha($dimg, true);        break;    default:        break;}// end changes$wm = $w/$nw;$hm = $h/$nh;// ...


if the code of the correct answer don't work try this :

    //After imagecreatetruecolor():$white = imagecolorallocate($dimg, 255, 255, 255); imagefill($dimg,0,0,$white); 


The order of operations is important. for .gif images i found that i needed to copy resized image first, then assign the black background as transparent. for PNGs I found the code below resized images and kept the transparency backgrounds.

also, this code worked for me...

$resized_image = imagecreatetruecolor($target_width, $target_height);switch ( $asset->a_mime_type ){    case 'image/jpeg':        imagecopyresampled($resized_image, $source, 0, 0, 0, 0, $target_width, $target_height, $asset->a_image_width, $asset->a_image_height);        $r = imagejpeg($resized_image,$file_name);        break;    case 'image/png':        imagealphablending($resized_image, FALSE);        imagesavealpha($resized_image, TRUE);        imagecopyresampled($resized_image, $source, 0, 0, 0, 0, $target_width, $target_height, $asset->a_image_width, $asset->a_image_height);        $r = @imagepng($resized_image,$file_name);        break;    case 'image/gif':        imagecopyresampled($resized_image, $source, 0, 0, 0, 0, $target_width, $target_height, $asset->a_image_width, $asset->a_image_height);        $background = imagecolorallocate($resized_image, 0, 0, 0);         imagecolortransparent($resized_image, $background);        $r = @imagegif($resized_image,$file_name);        break;}