一个脚本,用于重写不同大小的特定宽度的所有图像?

时间:2011-07-03 23:41:33

标签: php gd

我正在使用带有PHP的GD库。

基本上,我已经进行了设计更改,需要调整一大堆一定宽度的图像。

即876px宽的任何东西都需要是828px。

有没有办法遍历目录中的所有JPG文件,检查它们的宽度尺寸,如果它们等于X,那么抓住它们现有的文件名,重新缩放到相同的名称?

2 个答案:

答案 0 :(得分:1)

那里有很多图像调整大小的脚本......只是google ...但如果你想自己构建一些东西,你基本上会使用getimagesize imagecopyresampled

答案 1 :(得分:1)

只需在循环中使用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);
    }
}