Оптимизация изображений

Код


function compressImage($image_link, $ImageQuality){    
    //Open Source Image directory, loop through each Image and resize it.
    $checkValidImage = @getimagesize($image_link);
    //Continue only if 2 given parameters are true
    if (file_exists($image_link) && $checkValidImage)   {
        //Image looks valid, resize.
        resizeImage($image_link, $image_link, $checkValidImage[0], $checkValidImage[1], $ImageQuality);
    }
}
//Function that resizes image.
function resizeImage($SrcImage, $DestImage, $MaxWidth, $MaxHeight, $ImageQuality){
    list($iWidth, $iHeight, $type) = getimagesize($SrcImage);
    $ImageScale = min($MaxWidth / $iWidth, $MaxHeight / $iHeight);
    $NewWidth = ceil($ImageScale * $iWidth);
    $NewHeight = ceil($ImageScale * $iHeight);
    $NewCanves = imagecreatetruecolor($NewWidth, $NewHeight);
    switch (strtolower(image_type_to_mime_type($type))) {
        case 'image/jpeg': $NewImage = imagecreatefromjpeg($SrcImage); break;
        case 'image/JPEG': $NewImage = imagecreatefromjpeg($SrcImage); break;
        case 'image/png': $NewImage = imagecreatefrompng($SrcImage); break;
        case 'image/PNG':  $NewImage = imagecreatefrompng($SrcImage); break;
        case 'image/gif': $NewImage = imagecreatefromgif($SrcImage);  break;
        default: return false;
    }
    // Resize Image
    if (imagecopyresampled($NewCanves, $NewImage, 0, 0, 0, 0, $NewWidth, $NewHeight,
        $iWidth, $iHeight)) {
        // copy file
        if (imagejpeg($NewCanves, $DestImage, $ImageQuality)) {
            imagedestroy($NewCanves);
            return true;
        }
    }
}

Пример