我想要一个脚本,可以将所有图像转换为缩略图,并将这些新缩略图保存在新文件夹中。我很幸运,从http://webcheatsheet.com/php/create_thumbnail_images.php找到了一个几乎完美运行的代码
唯一的问题是,如果“上传”文件夹中有一个文件夹(在代码末尾定义),那么我会得到“注意:未定义的索引:扩展名”。代码没有卡住,我仍然得到缩略图,但错误消息很烦人。
我尝试放入 isset 函数,但犯了一些错误,因为我仍然无法阻止脚本对文件夹起作用。该代码对任何其他文件的反应都不同,因此似乎是文件夹名称中缺少扩展名而困扰了代码。
我可以轻松地从“上传”文件夹中删除任何文件夹,并将缩略图的路径放在其他地方,但我也想让它在没有错误消息的情况下工作,以防万一我碰巧有文件夹在这些图像文件夹中。
// parse path for the extension
$info = pathinfo($pathToImages . $fname);
// continue only if this is a JPEG image
//print_r($info);
if ( strtolower($info['extension']) == 'jpg' ) { // reacts on the folder with no extension name and gives an error
echo "Creating thumbnail for {$fname} <br />";
// load image and get image size
$img = imagecreatefromjpeg( "{$pathToImages}{$fname}" );
$width = imagesx( $img );
$height = imagesy( $img );
// calculate thumbnail size
$new_width = $thumbWidth;
$new_height = floor( $height * ( $thumbWidth / $width ) );
// create a new temporary image
$tmp_img = imagecreatetruecolor( $new_width, $new_height );
// copy and resize old image into new image
imagecopyresized( $tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height );
// save thumbnail into a file
imagejpeg( $tmp_img, "{$pathToThumbs}{$fname}" );
}
Run Code Online (Sandbox Code Playgroud)
}
完整代码在上面的链接中。
pathinfo文档解释:
笔记:
如果路径没有扩展名,则不会返回任何扩展名元素
因此,为了避免出现通知,您只需在尝试使用它之前检查该值是否可用:
if( isset($info['extension']) AND strtolower($info['extension']) == 'jpg'){
//do sutff
}
Run Code Online (Sandbox Code Playgroud)
或者isset(...)您可以使用array_keys_exists('extension', $info).