self::$maxWidth) { $newWidth = self::$maxWidth; $newHeight = (int) (self::$maxWidth / $aspectRatio); } // Resize based on height if it exceeds maxHeight or if new width based on maxHeight is less than maxWidth if ($newHeight > self::$maxHeight) { $newHeight = self::$maxHeight; $newWidth = (int) (self::$maxHeight * $aspectRatio); } // Final check to ensure it fits within both dimensions after initial adjustments if ($newWidth > self::$maxWidth) { $newWidth = self::$maxWidth; $newHeight = (int) (self::$maxWidth / $aspectRatio); } if ($newHeight > self::$maxHeight) { $newHeight = self::$maxHeight; $newWidth = (int) (self::$maxHeight * $aspectRatio); } $image = null; switch ($mimeType) { case 'image/jpeg': $image = imagecreatefromjpeg($imagePath); break; case 'image/png': $image = imagecreatefrompng($imagePath); break; case 'image/gif': $image = imagecreatefromgif($imagePath); break; default: error_log("ImageProcessor: Unsupported image type for resizing: " . $mimeType); return false; // Unsupported image type for resizing } if (!$image) { return false; } $resizedImage = imagecreatetruecolor($newWidth, $newHeight); // Preserve transparency for PNG and GIF if ($mimeType == 'image/png') { imagealphablending($resizedImage, false); imagesavealpha($resizedImage, true); $transparent = imagecolorallocatealpha($resizedImage, 255, 255, 255, 127); imagefilledrectangle($resizedImage, 0, 0, $newWidth, $newHeight, $transparent); } elseif ($mimeType == 'image/gif') { $trnprt_indx = imagecolortransparent($image); if ($trnprt_indx >= 0) { // Get the transparent color from the original image $trnprt_color = imagecolorsforindex($image, $trnprt_indx); // Allocate the same color in the new image $trnprt_indx = imagecolorallocate($resizedImage, $trnprt_color['red'], $trnprt_color['green'], $trnprt_color['blue']); imagefill($resizedImage, 0, 0, $trnprt_indx); imagecolortransparent($resizedImage, $trnprt_indx); } } imagecopyresampled($resizedImage, $image, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height); $success = false; switch ($mimeType) { case 'image/jpeg': $success = imagejpeg($resizedImage, $imagePath, 90); // 90% quality break; case 'image/png': $success = imagepng($resizedImage, $imagePath); break; case 'image/gif': $success = imagegif($resizedImage, $imagePath); break; } imagedestroy($image); imagedestroy($resizedImage); return $success; } }