我将GD库与PHP一起使用。
基本上,我已经做了一个设计更改,需要调整一整束一定宽度的图像的大小。
任何876像素宽的东西都需要828像素。
有没有一种方法可以循环浏览目录中的所有JPG文件,检查它们的宽度尺寸,如果它们等于X,那么获取它们现有的文件名,重新缩放到相同的名称?
只需要在循环中使用imagecopyresampled()
。
$path = "/my/path/to/jpgs";
$targetWidth = 876;
$newWidth = 828;
$imageQuality = 95;
if (is_dir($path)) {
$dHandle = opendir($path);
if ($dHandle) {
while (($cFileName = readdir($dHandle)) !== false) {
if (!preg_match("/'.jpg$/", $cFileName)) {
continue;
}
$cImagePath = $path . $cFileName;
list ($cWidth, $cHeight) = getimagesize($cImagePath);
if ($cWidth == $targetWidth) {
$cImage = imagecreatefromjpeg($cImagePath);
if ($cImage === false) {
echo "Error reading: " . $cImagePath . "'n";
continue;
}
$cNewHeight = round($cHeight * ($newWidth / $cWidth));
$cNewImage = imagecreatetruecolor($newWidth, $cNewHeight);
imagecopyresampled($cNewImage, $cImage, 0, 0, 0, 0, $newWidth, $cNewHeight, $cWidth, $cHeight);
if (imagejpeg($cNewImage, $cImagePath, $imageQuality) === false) {
echo "Error writing: " . $cImagePath . "'n";
continue;
}
}
}
closedir($dHandle);
}
}
有很多调整图像大小的脚本。。。只是谷歌。。。但是,如果你想自己构建一些东西,你基本上会使用getimagesize和imagecopy重采样