Skip to content

Instantly share code, notes, and snippets.

@bachloxo
Forked from janzikan/resize_image.php
Created April 26, 2020 11:22
Show Gist options
  • Save bachloxo/b4f593f6c2f1ba3cc02724f921db5464 to your computer and use it in GitHub Desktop.
Save bachloxo/b4f593f6c2f1ba3cc02724f921db5464 to your computer and use it in GitHub Desktop.

Revisions

  1. @janzikan janzikan renamed this gist Feb 15, 2014. 1 changed file with 0 additions and 0 deletions.
    File renamed without changes.
  2. @janzikan janzikan created this gist Jun 26, 2012.
    58 changes: 58 additions & 0 deletions gistfile1.aw
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,58 @@
    /**
    * Resize image - preserve ratio of width and height.
    * @param string $sourceImage path to source JPEG image
    * @param string $targetImage path to final JPEG image file
    * @param int $maxWidth maximum width of final image (value 0 - width is optional)
    * @param int $maxHeight maximum height of final image (value 0 - height is optional)
    * @param int $quality quality of final image (0-100)
    * @return bool
    */
    function resizeImage($sourceImage, $targetImage, $maxWidth, $maxHeight, $quality = 80)
    {
    // Obtain image from given source file.
    if (!$image = @imagecreatefromjpeg($sourceImage))
    {
    return false;
    }

    // Get dimensions of source image.
    list($origWidth, $origHeight) = getimagesize($sourceImage);

    if ($maxWidth == 0)
    {
    $maxWidth = $origWidth;
    }

    if ($maxHeight == 0)
    {
    $maxHeight = $origHeight;
    }

    // Calculate ratio of desired maximum sizes and original sizes.
    $widthRatio = $maxWidth / $origWidth;
    $heightRatio = $maxHeight / $origHeight;

    // Ratio used for calculating new image dimensions.
    $ratio = min($widthRatio, $heightRatio);

    // Calculate new image dimensions.
    $newWidth = (int)$origWidth * $ratio;
    $newHeight = (int)$origHeight * $ratio;

    // Create final image with new dimensions.
    $newImage = imagecreatetruecolor($newWidth, $newHeight);
    imagecopyresampled($newImage, $image, 0, 0, 0, 0, $newWidth, $newHeight, $origWidth, $origHeight);
    imagejpeg($newImage, $targetImage, $quality);

    // Free up the memory.
    imagedestroy($image);
    imagedestroy($newImage);

    return true;
    }

    /**
    * Example
    * resizeImage('image.jpg', 'resized.jpg', 200, 200);
    */