<p>The following PHP code snippet uses GD to resize a browser-uploaded PNG to 128x128. It works great, except that the transparent areas in the original image are being replaced with a solid color- black in my case. </p>

<p>Even though <code>imagesavealpha</code> is set, something isn't quite right.</p>

<p>What's the best way to preserve the transparency in the resampled image?</p>

<pre><code>$uploadTempFile = $myField[ 'tmp_name' ]
list( $uploadWidth, $uploadHeight, $uploadType ) 
  = getimagesize( $uploadTempFile );

$srcImage = imagecreatefrompng( $uploadTempFile );    
imagesavealpha( $targetImage, true );

$targetImage = imagecreatetruecolor( 128, 128 );
imagecopyresampled( $targetImage, $srcImage, 
                    0, 0, 
                    0, 0, 
                    128, 128, 
                    $uploadWidth, $uploadHeight );

imagepng(  $targetImage, 'out.png', 9 );
</code></pre>

[{'answer_id': 32270, 'author': 'ceejayoz', 'author_id': 1902010, 'author_profile': 'https://Stackoverflow.com/users/1902010', 'pm_score': 4, 'selected': False, 'text': '<p>I believe this should do the trick:</p>\n\n<pre><code>$srcImage = imagecreatefrompng($uploadTempFile);\nimagealphablending($srcImage, false);\nimagesavealpha($srcImage, true);\n</code></pre>\n\n<p><em>edit:</em> Someone in the PHP docs claims <code>imagealphablending</code> should be true, not false. YMMV.</p>\n'}, {'answer_id': 32302, 'author': 'Cheekysoft', 'author_id': 1820, 'author_profile': 'https://Stackoverflow.com/users/1820', 'pm_score': 9, 'selected': True, 'text': "<pre><code>imagealphablending( $targetImage, false );\nimagesavealpha( $targetImage, true );\n</code></pre>\n\n<p>did it for me. Thanks ceejayoz.</p>\n\n<p>note, the target image needs the alpha settings, not the source image.</p>\n\n<p>Edit:\nfull replacement code. See also answers below and their comments. This is not guaranteed to be be perfect in any way, but did achieve my needs at the time.</p>\n\n<pre><code>$uploadTempFile = $myField[ 'tmp_name' ]\nlist( $uploadWidth, $uploadHeight, $uploadType ) \n  = getimagesize( $uploadTempFile );\n\n$srcImage = imagecreatefrompng( $uploadTempFile ); \n\n$targetImage = imagecreatetruecolor( 128, 128 );   \nimagealphablending( $targetImage, false );\nimagesavealpha( $targetImage, true );\n\nimagecopyresampled( $targetImage, $srcImage, \n                    0, 0, \n                    0, 0, \n                    128, 128, \n                    $uploadWidth, $uploadHeight );\n\nimagepng(  $targetImage, 'out.png', 9 );\n</code></pre>\n"}, {'answer_id': 37364, 'author': 'Kalle', 'author_id': 3908, 'author_profile': 'https://Stackoverflow.com/users/3908', 'pm_score': 2, 'selected': False, 'text': "<p>Regrading the preserve transparency, then yes like stated in other posts imagesavealpha() have to be set to true, to use the alpha flag imagealphablending() must be set to false else it doesn't work.</p>\n\n<p>Also I spotted two minor things in your code:</p>\n\n<ol>\n<li>You don't need to call <code>getimagesize()</code> to get the width/height for <code>imagecopyresmapled()</code></li>\n<li>The <code>$uploadWidth</code> and <code>$uploadHeight</code> should be <code>-1</code> the value, since the cordinates starts at <code>0</code> and not <code>1</code>, so it would copy them into an empty pixel. Replacing it with: <code>imagesx($targetImage) - 1</code> and <code>imagesy($targetImage) - 1</code>, relativily should do :)</li>\n</ol>\n"}, {'answer_id': 291766, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 5, 'selected': False, 'text': '<p>Why do you make things so complicated? the following is what I use and so far it has done the job for me.</p>\n\n<pre><code>$im = ImageCreateFromPNG($source);\n$new_im = imagecreatetruecolor($new_size[0],$new_size[1]);\nimagecolortransparent($new_im, imagecolorallocate($new_im, 0, 0, 0));\nimagecopyresampled($new_im,$im,0,0,0,0,$new_size[0],$new_size[1],$size[0],$size[1]);\n</code></pre>\n'}, {'answer_id': 1302888, 'author': 'Linus Unnebäck', 'author_id': 148072, 'author_profile': 'https://Stackoverflow.com/users/148072', 'pm_score': 3, 'selected': False, 'text': "<p>I suppose that this might do the trick:</p>\n\n<pre><code>$uploadTempFile = $myField[ 'tmp_name' ]\nlist( $uploadWidth, $uploadHeight, $uploadType ) \n  = getimagesize( $uploadTempFile );\n\n$srcImage = imagecreatefrompng( $uploadTempFile );\n\n$targetImage = imagecreatetruecolor( 128, 128 );\n\n$transparent = imagecolorallocate($targetImage,0,255,0);\nimagecolortransparent($targetImage,$transparent);\nimagefilledrectangle($targetImage,0,0,127,127,$transparent);\n\nimagecopyresampled( $targetImage, $srcImage, \n                    0, 0, \n                    0, 0, \n                    128, 128, \n                    $uploadWidth, $uploadHeight );\n\nimagepng(  $targetImage, 'out.png', 9 );\n</code></pre>\n\n<p>The downside is that the image will be stripped of every 100% green pixels. Anyhow, hope it helps :)</p>\n"}, {'answer_id': 4618019, 'author': 'Jorrit Schippers', 'author_id': 261747, 'author_profile': 'https://Stackoverflow.com/users/261747', 'pm_score': 3, 'selected': False, 'text': "<p>An addition that might help some people:</p>\n\n<p>It is possible to toggle imagealphablending while building the image. I the specific case that I needed this, I wanted to combine some semi-transparent PNG's on a transparent background.</p>\n\n<p>First you set imagealphablending to false and fill the newly created true color image with a transparent color. If imagealphablending were true, nothing would happen because the transparent fill would merge with the black default background and result in black.</p>\n\n<p>Then you toggle imagealphablending to true and add some PNG images to the canvas, leaving some of the background visible (ie. not filling up the entire image).</p>\n\n<p>The result is an image with a transparent background and several combined PNG images.</p>\n"}, {'answer_id': 7731400, 'author': 'pricopz', 'author_id': 990203, 'author_profile': 'https://Stackoverflow.com/users/990203', 'pm_score': 3, 'selected': False, 'text': '<p>I have made a function for resizing image like JPEG/GIF/PNG with <code>copyimageresample</code> and PNG images still keep there transparency:</p>\n\n<pre><code>$myfile=$_FILES["youimage"];\n\nfunction ismyimage($myfile) {\n    if((($myfile["type"] == "image/gif") || ($myfile["type"] == "image/jpg") || ($myfile["type"] == "image/jpeg") || ($myfile["type"] == "image/png")) &amp;&amp; ($myfile["size"] &lt;= 2097152 /*2mb*/) ) return true; \n    else return false;\n}\n\nfunction upload_file($myfile) {         \n    if(ismyimage($myfile)) {\n        $information=getimagesize($myfile["tmp_name"]);\n        $mywidth=$information[0];\n        $myheight=$information[1];\n\n        $newwidth=$mywidth;\n        $newheight=$myheight;\n        while(($newwidth &gt; 600) || ($newheight &gt; 400 )) {\n            $newwidth = $newwidth-ceil($newwidth/100);\n            $newheight = $newheight-ceil($newheight/100);\n        } \n\n        $files=$myfile["name"];\n\n        if($myfile["type"] == "image/gif") {\n            $tmp=imagecreatetruecolor($newwidth,$newheight);\n            $src=imagecreatefromgif($myfile["tmp_name"]);\n            imagecopyresampled($tmp, $src, 0, 0, 0, 0, $newwidth, $newheight, $mywidth, $myheight);\n            $con=imagegif($tmp, $files);\n            imagedestroy($tmp);\n            imagedestroy($src);\n            if($con){\n                return true;\n            } else {\n                return false;\n            }\n        } else if(($myfile["type"] == "image/jpg") || ($myfile["type"] == "image/jpeg") ) {\n            $tmp=imagecreatetruecolor($newwidth,$newheight);\n            $src=imagecreatefromjpeg($myfile["tmp_name"]); \n            imagecopyresampled($tmp, $src, 0, 0, 0, 0, $newwidth, $newheight, $mywidth, $myheight);\n            $con=imagejpeg($tmp, $files);\n            imagedestroy($tmp);\n            imagedestroy($src);\n            if($con) {  \n                return true;\n            } else {\n                return false;\n            }\n        } else if($myfile["type"] == "image/png") {\n            $tmp=imagecreatetruecolor($newwidth,$newheight);\n            $src=imagecreatefrompng($myfile["tmp_name"]);\n            imagealphablending($tmp, false);\n            imagesavealpha($tmp,true);\n            $transparent = imagecolorallocatealpha($tmp, 255, 255, 255, 127);\n            imagefilledrectangle($tmp, 0, 0, $newwidth, $newheight, $transparent); \n            imagecopyresampled($tmp, $src, 0, 0, 0, 0, $newwidth, $newheight, $mywidth, $myheight);\n            $con=imagepng($tmp, $files);\n            imagedestroy($tmp);\n            imagedestroy($src);\n            if($con) {\n                return true;\n            } else {\n                return false;\n            }\n        }   \n    } else\n          return false;\n}\n</code></pre>\n'}, {'answer_id': 37871122, 'author': 'Md. Imadul Islam', 'author_id': 3950386, 'author_profile': 'https://Stackoverflow.com/users/3950386', 'pm_score': 0, 'selected': False, 'text': '<p>Here is my total test code. It works for me</p>\n\n<pre><code>$imageFileType = pathinfo($_FILES["image"]["name"], PATHINFO_EXTENSION);\n$filename = \'test.\' . $imageFileType;\nmove_uploaded_file($_FILES["image"]["tmp_name"], $filename);\n\n$source_image = imagecreatefromjpeg($filename);\n\n$source_imagex = imagesx($source_image);\n$source_imagey = imagesy($source_image);\n\n$dest_imagex = 400;\n$dest_imagey = 600;\n$dest_image = imagecreatetruecolor($dest_imagex, $dest_imagey);\n\nimagecopyresampled($dest_image, $source_image, 0, 0, 0, 0, $dest_imagex, $dest_imagey, $source_imagex, $source_imagey);\n\nimagesavealpha($dest_image, true);\n$trans_colour = imagecolorallocatealpha($dest_image, 0, 0, 0, 127);\nimagefill($dest_image, 0, 0, $trans_colour);\n\nimagepng($dest_image,"test1.png",1);\n</code></pre>\n'}, {'answer_id': 46084683, 'author': 'nsinvocation', 'author_id': 1804311, 'author_profile': 'https://Stackoverflow.com/users/1804311', 'pm_score': 0, 'selected': False, 'text': "<p>Pay attention to the source image's <code>width</code> and <code>height</code> values which are passed to <code>imagecopyresampled</code> function. If they are bigger than actual source image size, the rest of image area will be filled with black color.  </p>\n"}, {'answer_id': 51810856, 'author': 'Marco', 'author_id': 2969320, 'author_profile': 'https://Stackoverflow.com/users/2969320', 'pm_score': 0, 'selected': False, 'text': "<p>I combined the answers from ceejayoz and Cheekysoft, which gave the best result for me. Without imagealphablending() and imagesavealpha() the image is not clear:</p>\n\n<pre><code>$img3 = imagecreatetruecolor(128, 128);\nimagecolortransparent($img3, imagecolorallocate($img3, 0, 0, 0));\nimagealphablending( $img3, false );\nimagesavealpha( $img3, true );\nimagecopyresampled($img3, $srcImage, 0, 0, 0, 0, 128, 128, $uploadWidth, $uploadHeight);\nimagepng($img3, 'filename.png', 9);\n</code></pre>\n"}, {'answer_id': 72346188, 'author': 'Lepy', 'author_id': 11582724, 'author_profile': 'https://Stackoverflow.com/users/11582724', 'pm_score': 0, 'selected': False, 'text': '<p>For anyone having problems with <code>imagecopyresampled</code> or <code>imagerotate</code> with black bars on background, I have found a code example here:</p>\n<p><a href="https://qna.habr.com/q/646622#answer_1417035" rel="nofollow noreferrer">https://qna.habr.com/q/646622#answer_1417035</a></p>\n<pre><code>        // get image sizes (X,Y)\n        $wx = imagesx($imageW);\n        $wy = imagesy($imageW);\n\n        // create a new image from the sizes on transparent canvas\n        $new = imagecreatetruecolor($wx, $wy);\n\n        $transparent = imagecolorallocatealpha($new, 0, 0, 0, 127);\n        $rotate = imagerotate($imageW, 280, $transparent);\n        imagealphablending($rotate, true);\n        imagesavealpha($rotate, true);\n\n        // get the newest image X and Y\n        $ix = imagesx($rotate);\n        $iy = imagesy($rotate);\n\n        //copy the image to the canvas\n        imagecopyresampled($destImg, $rotate, 940, 2050, 0, 0, $ix, $iy, $ix, $iy);\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/32243', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1820/']