image resize, maintain png transparency
function resizePng($im, $dst_width, $dst_height) {
$width = imagesx($im);
$height = imagesy($im);
$newImg = imagecreatetruecolor($dst_width, $dst_height);
imagealphablending($newImg, false);
imagesavealpha($newImg, true);
$transparent = imagecolorallocatealpha($newImg, 255, 255, 255, 127);
imagefilledrectangle($newImg, 0, 0, $width, $height, $transparent);
imagecopyresampled($newImg, $im, 0, 0, 0, 0, $dst_width, $dst_height, $width, $height);
return $newImg;
}list($imgWidth, $imgHeight, $image_type) = getimagesize($file);
function getImage($file, $image_type)
{
$image;
if($image_type == IMAGETYPE_JPEG) {
$image = imagecreatefromjpeg($file);
} else if($image_type == IMAGETYPE_GIF) {
$image = imagecreatefromgif($file);
} else if($image_type == IMAGETYPE_PNG) {
$image = imagecreatefrompng($file);
} else {
$image = imagecreatefromjpeg($file);
}
return $image;
}
function saveImageJPEG($image, $file)
{
imagejpeg($image,$file);
imagedestroy($image);
}
function saveImagePNG($image, $file)
{
//header("Content-type: image/png");
imagepng($image,$file);
imagedestroy($image);
}
function resizeImage($file)
{
list($imgWidth, $imgHeight, $image_type) = getimagesize($file);
$image = getImage($file, $image_type);
$resizedWidth = $imgWidth;
$resizedHeight = $imgHeight;
$proportion = $imgWidth > $imgHeight ? $imgWidth / $imgHeight : $imgHeight / $imgWidth;
if($proportion >= 1)
{
if ($imgWidth > 1000) {
$resizedWidth = 1000;
$resizedHeight = ($resizedWidth * $imgHeight) / $imgWidth;
}
if ($resizedHeight > 800) {
$oldHeight = $resizedHeight;
$resizedHeight = 800;
$resizedWidth = ($resizedHeight * $resizedWidth) / $oldHeight;
}
}
else
{
if ($imgHeight > 1000) {
$resizedHeight = 1000;
$resizedWidth = ($resizedHeight * $imgWidth) / $imgHeight;
}
if ($resizedWidth > 800) {
$oldWidth = $resizedWidth;
$resizedWidth = 800;
$resizedHeight = ($resizedWidth * $resizedHeight) / $oldWidth;
}
}
//solve png issues
/*imagealphablending($image, false);
imagesavealpha($image, true);
$transparent = imagecolorallocatealpha($image, 0, 0, 0, 127);
imagefilledrectangle($image, 0, 0, $imgWidth, $imgHeight, $transparent);*/
/* imagesavealpha($image, true);
$trans_colour = imagecolorallocatealpha($image, 0, 0, 0, 127);
imagefill($image, 0, 0, $trans_colour); */
$resizedImage = imagecreatetruecolor($resizedWidth, $resizedHeight);
///////////////
imagealphablending($resizedImage, false);
imagesavealpha($resizedImage, true);
$transparent = imagecolorallocatealpha($resizedImage, 255, 255, 255, 127);
imagefilledrectangle($resizedImage, 0, 0, $width, $height, $transparent);
///////////////
imagecopyresampled($resizedImage, $image, 0, 0, 0, 0, $resizedWidth, $resizedHeight, $imgWidth, $imgHeight);
if ( $image_type == IMAGETYPE_JPEG) saveImageJPEG($resizedImage, $file);
if ( $image_type == IMAGETYPE_PNG) saveImagePNG($resizedImage, $file);
}