如何使用PHP批量调整图像大小

3

我正在维护一个旧网站。现在我的客户想要添加超过6000个产品。这些产品图片有不同的尺寸。我需要应用批处理。我必须将它们全部调整为230x230的缩略图大小。有没有办法从PHP中完成?如果有,如何实现?

我必须从位于主图片文件夹内的不同文件夹中读取所有内容。该图片文件夹有40个子文件夹。每个文件夹名称都是类别名称,其中包含的图片是产品(图片)。

if(imagecopyresampled($NewCanves, $NewImage,0, 0, 0, 0, $NewWidth, $NewHeight, $iWidth, $iHeight))
{
    // copy file
    if(imagejpeg($NewCanves,$DestImage,$Quality))
    {
        imagedestroy($NewCanves);
        return true;
    }
}

当然有方法可以做到这一点——但是如果您通过HTTP请求触发它,并希望一次运行所有文件,您很可能会遇到执行时间和可能的内存限制。最好从命令行中进行操作,如果您有权限,那么它不必在PHP中实现,像Imagick这样的工具也允许批量转换。 - CBroe
3个回答

5

使用PHP,您可以使用以下方式读取文件夹内的文件:

$images= glob("*"); // * will address all files
// or
$images= glob("*.jpg"); // this will address only jpg images

然后循环遍历$images

foreach ($images as $filename) {
   //resize the image
   if(resizeImage($imagePath,$destPath,$NewImageWidth,$NewImageHeight,$Quality)){
     echo $filename.' resize Success!<br />';
   }
}

function resizeImage($SrcImage,$DestImage, $MaxWidth,$MaxHeight,$Quality)
{
    list($iWidth,$iHeight,$type)    = getimagesize($SrcImage);

    //if you dont want to rescale image

    $NewWidth=$MaxWidth;
    $NewHeight=$MaxHeight;
    $NewCanves              = imagecreatetruecolor($NewWidth, $NewHeight);

    // Resize Image
    if(imagecopyresampled($NewCanves, $NewImage,0, 0, 0, 0, $NewWidth, $NewHeight, $iWidth, $iHeight))
     {
        // copy file
        if(imagejpeg($NewCanves,$DestImage,$Quality))
        {
            imagedestroy($NewCanves);
            return true;
        }
    }
}

2
不客气。顺便问一下,你卡在哪里了?你也可以使用 $folder = "images"; 读取子目录中的目录。$results = scandir($folder); - GaurabDahal

1
您可以使用 shell 脚本轻松实现此操作,但如果您必须在 PHP 中执行此操作,则应将所有图像放入同一目录中,并使用循环遍历该目录。
$img= new Imagick($srcpath);
$img->resizeImage($width,$height,Imagick::FILTER_BOX,1,true);

http://php.net/manual/en/function.imagick-resizeimage.php


1
你可以使用此库轻松调整单个/多个图像的大小。只需4-5行PHP代码,你就可以轻松管理。
此外,还可以通过参数传递许多其他选项,如高度、宽度、img_dir。

https://github.com/hsleonis/image-resizer


require_once ('class.imageresizer.php');

// 创建缩略图
$args = array(
    'height'    => 975,
    'width'     => 650,
    'is_crop_hard' => 1
);
$img = new ImageResizer($args);
$img->create();</code>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接