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

时间:2014-03-14 10:53:08

标签: php batch-processing

我正在维护一个旧网站。现在我的客户想要添加超过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;
    }
}

3 个答案:

答案 0 :(得分: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;
        }
    }
}

答案 1 :(得分: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

答案 2 :(得分:0)

您可以使用此库轻松调整单个/多个图像的大小。 PHP代码只有4-5行,因此您可以轻松管理。

此外,还可以传递高度,宽度,img_dir等参数中的许多其他选项。

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


require_once ('class.imageresizer.php');

// Create thumbnails
$args = array(
    'height'    => 975,
    'width'     => 650,
    'is_crop_hard' => 1
);
$img = new ImageResizer($args);
$img->create();</code>