Detect JPEG image quality

后端 未结 7 879
借酒劲吻你
借酒劲吻你 2021-02-10 10:25

I allow users to upload images. However, I want to keep JPEG quality not more than 90%. What I plan to do is to detect the current quality: - If less than 90% do nothing - If mo

7条回答
  •  名媛妹妹
    2021-02-10 10:48

    Here is a PHP function that tries all available methods of getting quality (that I know of):

    /* Try to detect quality of jpeg.
       If not possible, nothing is returned (null). Otherwise quality is returned (int)
        */
    function detectQualityOfJpg($filename)
    {
        // Try Imagick extension
        if (extension_loaded('imagick') && class_exists('Imagick')) {
            $img = new Imagick($filename);
    
            // The required function is available as from PECL imagick v2.2.2
            if (method_exists($img, 'getImageCompressionQuality')) {
                return $img->getImageCompressionQuality();
            }
        }
    
        if (function_exists('shell_exec')) {
    
        // Try Imagick
            $quality = shell_exec("identify -format '%Q' " . $filename);
            if ($quality) {
                return intval($quality);
            }
    
            // Try GraphicsMagick
            $quality = shell_exec("gm identify -format '%Q' " . $filename);
            if ($quality) {
                return intval($quality);
            }
        }
    }
    

提交回复
热议问题