Created
April 7, 2016 21:28
-
-
Save index0h/827b1a8c8d58a4e32e51b0e588e46600 to your computer and use it in GitHub Desktop.
image_resize.php
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$sourcePath = ''; | |
$destinationPath = ''; | |
$maxHeight = 1024; | |
$maxWith = 768; | |
$ratio = $maxWith / $maxHeight; | |
$dir = new DirectoryIterator($sourcePath); | |
foreach ($dir as $file) { | |
if ($file->isDot()) { | |
continue; | |
} | |
$sourceImage = null; | |
$filePath = $file->getPathname(); | |
switch (strtolower($file->getExtension())) { | |
case 'jpg': | |
case 'jpeg': | |
$sourceImage = imagecreatefromjpeg($filePath); | |
break; | |
case 'png': | |
$sourceImage = imagecreatefrompng($filePath); | |
break; | |
case 'gif': | |
$sourceImage = imagecreatefromgif($filePath); | |
break; | |
} | |
if (is_null($sourceImage)) { | |
continue; | |
} | |
$scalePercent = null; | |
list($currentWidth, $currentHeight) = getimagesize($filePath); | |
$currentRatio = $currentHeight / $currentWidth; | |
if ($currentRatio > $ratio) { | |
$newHeight = $currentHeight; | |
$newWidth = $currentHeight * $ratio; | |
} else { | |
$newHeight = $currentWidth * $ratio; | |
$newWidth = $currentWidth; | |
} | |
$destinationImage = imagecreatetruecolor($newWidth, $newHeight); | |
imagecopyresampled( | |
$destinationImage, | |
$sourceImage, | |
0, | |
0, | |
0, | |
0, | |
$newWidth, | |
$newHeight, | |
$currentWidth, | |
$currentHeight | |
); | |
$destinationImagePath = $destinationPath . '/' . $file->getBasename($file->getExtension()) . 'jpg'; | |
imagejpeg($destinationImage, $destinationImagePath, 80); | |
imagedestroy($destinationImage); | |
imagedestroy($sourceImage); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment