Skip to content

Instantly share code, notes, and snippets.

@inkless
Last active December 15, 2015 06:49
Show Gist options
  • Save inkless/5218608 to your computer and use it in GitHub Desktop.
Save inkless/5218608 to your computer and use it in GitHub Desktop.
使用方法: 将该文件存放在任何php环境。运行方法两种: 1. 命令行模式 php resizeimage.php {path} 2. 浏览器模式 localhost/resizeimage.php?path=. 注意路径最好使用相对路径
<?php
$dir = '';
if (isset($argv[1])) $dir = $argv[1];
if ($_REQUEST['path']) $dir = $_REQUEST['path'];
if (!$dir) {
echo "Path not specified! Please use `localhost/resizeimage.php?path=.` or `php resizeimage.php {path}`\n";exit;
}
runindir($dir);
function resize($img, $newfilename, $w='', $h='') {
//Check if GD extension is loaded
if (!extension_loaded('gd') && !extension_loaded('gd2')) {
trigger_error("GD is not loaded", E_USER_WARNING);
return false;
}
//Get Image size info
list($width, $height) = getimagesize($img);
if (!$w) $w = $width / 2;
if (!$h) $h = $height / 2;
$imgInfo = getimagesize($img);
switch ($imgInfo[2]) {
case 1:
$im = imagecreatefromgif($img);
break;
case 2:
$im = imagecreatefromjpeg($img);
break;
case 3:
$im = imagecreatefrompng($img);
break;
default:
trigger_error('Unsupported filetype!', E_USER_WARNING);
break;
}
//If image dimension is smaller, do not resize
if ($imgInfo[0] <= $w && $imgInfo[1] <= $h) {
$nHeight = $imgInfo[1];
$nWidth = $imgInfo[0];
} else {
//yeah, resize it, but keep it proportional
if ($w / $imgInfo[0] > $h / $imgInfo[1]) {
$nWidth = $w;
$nHeight = $imgInfo[1] * ($w / $imgInfo[0]);
} else {
$nWidth = $imgInfo[0] * ($h / $imgInfo[1]);
$nHeight = $h;
}
}
$nWidth = round($nWidth);
$nHeight = round($nHeight);
$newImg = imagecreatetruecolor($nWidth, $nHeight);
/* Check if this image is PNG or GIF, then set if Transparent*/
if (($imgInfo[2] == 1) OR($imgInfo[2] == 3)) {
imagealphablending($newImg, false);
imagesavealpha($newImg, true);
$transparent = imagecolorallocatealpha($newImg, 255, 255, 255, 127);
imagefilledrectangle($newImg, 0, 0, $nWidth, $nHeight, $transparent);
}
imagecopyresampled($newImg, $im, 0, 0, 0, 0, $nWidth, $nHeight, $imgInfo[0], $imgInfo[1]);
//Generate the file, and rename it to $newfilename
switch ($imgInfo[2]) {
case 1:
imagegif($newImg, $newfilename);
break;
case 2:
imagejpeg($newImg, $newfilename);
break;
case 3:
imagepng($newImg, $newfilename);
break;
default:
trigger_error('Failed resize image!', E_USER_WARNING);
break;
}
return $newfilename;
}
function runindir($dir) {
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
while (($file = readdir($dh)) !== false) {
if ($pos = strpos($file, '_2x.')) {
$name = substr($file, 0, $pos);
$type = substr($file, $pos+4);
$new_filename = $dir.'/'.$name.'.'.$type;
echo resize($dir.'/'.$file, $new_filename)."\n";
}
}
closedir($dh);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment