我成功地用以下命令运行了一个 cron 作业:
cd "public_html/wp-content/uploads/bpfb/" && mogrify -strip -resize 800x800'> *.jpeg *.jpg
这基本上是获取所有JPEG图像,并通过ImageMagick在特定文件夹中调整它们的大小。但是,问题是此命令将根据 cron 间隔一遍又一遍地处理"已处理"的图像。 我需要将所有文件保留在同一目录中,所以我正在寻找一种 cron(或 PHP 脚本)可以检测它是否已被处理并在下一个 cron 周期中排除这些文件的方法。
(请注意,我对 cron 或 PHP 脚本不太精通,所以非常感谢我的基本步骤)。
最好的解决方案是重命名或移动到另一个目录。
正如你所说你不能这样做,那么你可以创建一个使用 getimagesize() 或类似脚本来获取图像尺寸的 PHP 脚本,如果图像宽度和高度 = 800,那么你可以假设它已被处理。
不过,这不是最有效的解决方案。
未经测试的示例:
<?php
$imageDirectory = "/home/public_html/images/"; // Path to your images
// Read all files in directory. (You could put this in a function and call recursively if you have child directories.)
$files = scandir($imageDirectory);
foreach($files as $file)
{
if($file == '.' || $file == '..')
{
continue;
}
if(preg_match('/'.(jpg|jpeg)$/', $file))
{
list($width, $height, $type, $attr) = getimagesize($imageDirectory . $file);
// This is your image resize condition, change to suit your requirements
if($width > 800 && $height > 800)
{
// Resize Image Code Here
}
}
}
?>
如果您不信任图像源,则可能需要获取图像的实际 MIME 类型,而不是扩展匹配。
第二种方法是将处理的文件名记录到日志文件中,并与目录列表进行比较以查看它是否已被处理。
再次未经测试:
<?php
// Open log file so we can read and put processed image name onto array
$imageLogFilename = 'image.log';
$fh = fopen($imageLogFilename,'a+');
$processedFileNames = array();
$newProcessedFileNames = array();
// Read file line by line and add filename onto an array
if($fh)
{
while (($line = fgets($fh)) !== false)
{
$processedFileNames[] = trim($line);
}
fclose($fh);
}
else
{
die('error - could not open log for reading');
}
$imageDirectory = "/home/public_html/images/"; // Path to your images
// Read all files in image directory. (You could put this in a function and call recursively if you have child directories.)
$files = scandir($imageDirectory);
foreach($files as $file)
{
if($file == '.' || $file == '..')
{
continue;
}
// check if this image is in the already processed image array
if(in_array($file, $processedFileNames) === false)
{
// your resize code here
if($resizeResult == false)
{
die('Image Resizing Failed');
}
}
// Store all images on new array
$newProcessedFileNames[] = $file;
}
if(count($newProcessedFileNames) > 0)
{
// open logfile again but this time truncate and update with latest image filenames, so its up to date for next run.
$fh = fopen($imageLogFilename,'w');
if($fh)
{
foreach($newProcessedFileNames as $filename)
{
fwrite($fh,$filename . PHP_EOL);
}
fclose($fh);
}
else
{
die('error - could not write to log file');
}
}
fclose($fh);
?>
我建议用cron用你选择的语言调用脚本。
然后,您可以在其中添加逻辑以防止它再次处理图像。您可以将完成的日志放在不同的文件夹中,用前缀或后缀以不同的方式标记它们,或者您可以在某处保留日志。
Mogrify 有一个参数 -path,顺便说一下,您可以在其中将其写入另一个目录。