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?