0

I'm attempting to allow transparency when compressing a file upload.

I created a function in which it will change the image to a jpeg (no matter what is uploaded), however, my client wants the images to have transparency. For ease, what I will do is if the image is a PNG, I will save it out as a PNG with transparency enabled, otherwise, I will just save it as a "flat" jPEG.

Here is the function I created.

function resizeImage($image, $resizeHeight = null, $resizeWidth = null, $quality = 80)
{
    $img = getimagesize($image);
    $ext = explode(".",$image);

    list($width, $height, $type, $attr) = $img;

    if($resizeHeight == null)
    {
        //Getting the new height by dividing the image width by the height and multiplying by the new width.
        $resizeHeight = ($height/$width)*$resizeWidth;
    }
    if($resizeWidth == null)
    {
        //Getting the new width by dividing the image height by the width and multiplying by the new height.
        $resizeWidth = ($width/$height)*$resizeHeight;
    }

    $name = uniqid().time().".".$ext[count($ext)-1];

    if($img['mime'] == "image/jpeg")
    {
        $image = imagecreatefromjpeg($image);
    }
    else if($img['mime'] == "image/png")
    {
        $image = imagecreatefrompng($image);
    }

    $destImg = imagecreatetruecolor($resizeWidth, $resizeHeight);

    if(imagecopyresampled($destImg, $image, 0, 0, 0, 0, $resizeWidth, $resizeHeight, $width, $height))
    {
        if(imagejpeg($destImg, DIRUPLOADFOLDER.$name, $quality))
        {
            return $name;
        }
    }
}

Needless to say, this function only saves out as a JPEG. I tried replacing imagejpeg with imagepng but that didn't work (like it didn't at all create an image). What do I need to do in order to make sure that the saved out PNG will also save out with the original's transparency?

Majo0od
  • 2,278
  • 10
  • 33
  • 58
  • This post may help you: http://stackoverflow.com/questions/15246813/php-gd-transparent-background – mkabanen Jan 09 '14 at 16:42
  • That didn't really help, since the structure of my code is fairly different. All it did was create a black background. – Majo0od Jan 11 '14 at 15:35
  • For those who are more curious, this is what was most help to me http://stackoverflow.com/questions/32243/can-png-image-transparency-be-preserved-when-using-phps-gdlib-imagecopyresample – Majo0od Jan 11 '14 at 15:54

0 Answers0