Skip to content

Instantly share code, notes, and snippets.

@fians
Created January 3, 2018 10:24
Show Gist options
  • Select an option

  • Save fians/80405a143434fb4cb9379e95e4f6f0ee to your computer and use it in GitHub Desktop.

Select an option

Save fians/80405a143434fb4cb9379e95e4f6f0ee to your computer and use it in GitHub Desktop.

Revisions

  1. fians created this gist Jan 3, 2018.
    69 changes: 69 additions & 0 deletions optimize.php
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,69 @@
    /**
    * Optimize image image
    *
    * https://developers.google.com/speed/docs/insights/OptimizeImages
    * -sampling-factor 4:2:0 -strip -quality 85 -interlace JPEG -colorspace sRGB
    *
    * @access public
    * @param string $filePath Path of the file
    * @return string Raw image result from the process
    */
    public static function optimize($filePath)
    {
    /**
    * Compress image
    */
    $imagick = new Imagick();

    $rawImage = file_get_contents($filePath);

    $imagick->readImageBlob($rawImage);
    $imagick->stripImage();

    // Define image
    $width = $imagick->getImageWidth();
    $height = $imagick->getImageHeight();

    // Compress image
    $imagick->setImageCompressionQuality(85);

    $image_types = getimagesize($filePath);

    // Get thumbnail image
    $imagick->thumbnailImage($width, $height);

    // Set image as based its own type
    if ($image_types[2] === IMAGETYPE_JPEG)
    {
    $imagick->setImageFormat('jpeg');

    $imagick->setSamplingFactors(array('2x2', '1x1', '1x1'));

    $profiles = $imagick->getImageProfiles("icc", true);

    $imagick->stripImage();

    if(!empty($profiles)) {
    $imagick->profileImage('icc', $profiles['icc']);
    }

    $imagick->setInterlaceScheme(Imagick::INTERLACE_JPEG);
    $imagick->setColorspace(Imagick::COLORSPACE_SRGB);
    }
    else if ($image_types[2] === IMAGETYPE_PNG)
    {
    $imagick->setImageFormat('png');
    }
    else if ($image_types[2] === IMAGETYPE_GIF)
    {
    $imagick->setImageFormat('gif');
    }

    // Get image raw data
    $rawData = $imagick->getImageBlob();

    // Destroy image from memory
    $imagick->destroy();

    return $rawData;
    }