2012-11-01 61 views
2

真的要砸我的大脑,我一直在寻找这个2天以上。目录中的GD图像批处理

目标?点击/选择一个包含图像的子目录;在提交时,将使用GD在所选的整个DIR上运行批处理过程,在同一台服务器上的/ thumbs文件夹中创建大拇指。

状态?我可以一次为单个文件执行此操作,但需要一次执行多个文件。

这是我运作一次性代码:

$filename = "images/r13.jpg"; 

list($width,$height) = getimagesize($filename); 

$width_ratio = 166/$width; 
if ($height * $width_ratio <= 103) 
{ 
    $adjusted_width = 166; 
    $adjusted_height = $height * $width_ratio; 
} 
else 
{ 
    $height_ratio = 103/$height; 
    $adjusted_width = $width * $height_ratio; 
    $adjusted_height = 103; 
} 

$image_p = imagecreatetruecolor(166,103); 
$image = imagecreatefromjpeg($filename); 
imagecopyresampled($image_p,$image,ceil((166 - $adjusted_width)/2),ceil((103 - $adjusted_height)/2),0,0,ceil($adjusted_width),ceil($adjusted_height),$width,$height); 

imagejpeg($image_p,"images/thumbs/r13.jpg",70); 

正如你所看到的,该脚本靶向一个单一的文件,我想通过目录遍历指定名称代替。

(我也会看看ImageMagick的,但目前它不是一个选项。)

我会继续经历SO等,但任何帮助将是巨大的。

谢谢。

回答

3

你需要从这个代码做一个函数:

function processImage($filename){ 
    list($width,$height) = getimagesize($filename); 

    $width_ratio = 166/$width; 
    if ($height * $width_ratio <= 103) 
    { 
     $adjusted_width = 166; 
     $adjusted_height = $height * $width_ratio; 
    } 
    else 
    { 
     $height_ratio = 103/$height; 
     $adjusted_width = $width * $height_ratio; 
     $adjusted_height = 103; 
    } 

    $image_p = imagecreatetruecolor(166,103); 
    $image = imagecreatefromjpeg($filename); 
    imagecopyresampled($image_p,$image,ceil((166 - $adjusted_width)/2),ceil((103 - $adjusted_height)/2),0,0,ceil($adjusted_width),ceil($adjusted_height),$width,$height); 

    imagejpeg($image_p,"images/thumbs/".basename($filename),70); 
    imagedestroy($image_p); 
} 

请注意,这个函数的最后两行:它通过fiulename写拇指筑底,破坏资源,以释放内存。

现在目录应用此的所有文件:

foreach(glob('images/*.jpg') AS $filename){ 
    processImage($filename); 
} 

,基本上就是这样。

+0

dev-null-dweller,工作完美。谢谢(和R.S)这么快回复。我是新来的回答 - 我如何将这个问题标记为回答? –

+0

在答案的左侧应该有✅,只需单击它,它会变成绿色 –

+0

@ dev-null-dweller我试过你的解决方案,并将一些值改为150像素,然后当我运行它时,它可以工作,但是当我检查了缩略图,上面和下面都有这条黑线。原始尺寸大于150,这应该足以将图像裁剪为150像素。 – anagnam