使用php将图像批处理文件转换为灰度

时间:2010-03-12 14:33:58

标签: php batch-file gd

任何人都可以找到我在这里出错的地方。它应该在一个文件夹中创建图像的灰度副本,并将它们保存在另一个文件夹中。可能与我引用文件位置的方式有关。两个文件夹上的文件夹权限均为777.脚本运行时没有可见错误但未创建任何图像。

function grayscalecopy($targetfile, $outputfile){
$size = GetImageSize($targetfile);
$width = $size[1];
$height = $size[0];
$canvas = imagecreatetruecolor($width, $height);
$sourceimage = imagecreatefromjpeg($targetfile);
imagefilter($sourceimage, IMG_FILTER_GRAYSCALE);
imagecopy($canvas, $sourceimage, 0, 0, 0, 0, $width, $height);
imagejpeg($canvas, $outputfile, 95);
imagedestroy($sourceimage);
imagedestroy($canvas);
echo "Converted ".$targetfile." to grayscale as ".$outputfile." ".$width."x".$height."<br/>";
}

$serverfiles = glob("artworkimages/thumbs/*.*");
//$numbertocache = count($serverfiles);
$numbertocache = 10;
for ($i=0; $i<$numbertocache; $i++)
{
    $serverfilesshort=explode("/",$serverfiles[$i]);
    $serverfilesshort=$serverfilesshort[count($serverfilesshort)-1];
    grayscalecopy($serverfiles[$i], "artworkimages/thumbs/grays/".$serverfilesshort);
}

1 个答案:

答案 0 :(得分:1)

检查imagejpeg电话的结果。将您的代码更改为:

$result = imagejpeg($canvas, $outputfile, 95);
if($result)
{
    echo "Converted ".$targetfile." to grayscale as ".$outputfile." ".$width."x".$height."<br/>";
}
else
{
    echo "Could not save to $outputfile.<br>"
    if(!is_writable($outputfile)
        echo "The path was not writable";
}
imagedestroy($sourceimage);
imagedestroy($canvas);

这将有助于我们了解正在发生的事情。如果您得到“路径不可写”,请尝试使用绝对路径而不是相对路径,例如:

grayscalecopy($serverfiles[$i], dirname(__FILE__)."/artworkimages/thumbs/grays/".$serverfilesshort);