获取并显示某目录下的图片

<?php  
      
    $disp_width_max=150; // 最大显示宽度  
    $disp_height_max=80; // 最大显示高度  
      
    // 图片目录  
    $dir = dirname(__FILE__).'/watermarks';  
      
    if (is_dir($dir)) {  
            if ($dh = opendir($dir)) {  
                $i=0;  
                $watermarks=array();  
                while (($file = readdir($dh)) !== FALSE) {  
                    if(!preg_match('`\.png$`',$file)) continue;  
                    $watermarks[]=$file;  
                }  
                closedir($dh);  
                  
                // 根据文件名将数组排序  
                asort($watermarks);  
                  
                foreach($watermarks as $file){  
                    // 控制显示宽度  
                    $size=getimagesize($dir.'/'.$file);  
                    if($size[0] > $disp_width_max && $disp_width_max){  
                        $reduction=$disp_width_max / $size[0];  
                        $size[0]=$size[0]*$reduction;  
                        $size[1]=$size[1]*$reduction;  
                        $size[3]=sprintf('width="%d" height="%d"',$size[0],$size[1]);  
                          
                        // also restrain the height after a resize  
                        if($size[1] > $disp_height_max && $disp_height_max){  
                            $reduction=$disp_height_max / $size[1];  
                            $size[0]=$size[0]*$reduction;  
                            $size[1]=$size[1]*$reduction;  
                            $size[3]=sprintf('width="%d" height="%d"',$size[0],$size[1]);  
                        }  
                    }  
  
                    // 控制显示高度  
                    if($size[1] > $disp_height_max && $disp_height_max){  
                        $reduction=$disp_height_max / $size[1];  
                        $size[0]=$size[0]*$reduction;  
                        $size[1]=$size[1]*$reduction;  
                        $size[3]=sprintf('width="%d" height="%d"',$size[0],$size[1]);  
                    }  
  
                    echo '      <tr>',"\n",  
                         '       <td>',"\n",  
                         '        <input type="radio" value="',$file,'" name="watermark" /> ',  
                         '<img src="watermarks/',$file,'" ',$size[3],' alt="" />',"\n",  
                         '       </td>',"\n",  
                         '      </tr>',"\n";  
  
                    $i++;  
                }  
                if($i==0){  
                    // 如果目录下没有图片  
                    echo '     <tr>',"\n",  
                         '      <td>',"\n",  
                         '       在该目录下没有此类型文件。',"\n",  
                         '      </td>',"\n",  
                         '    </tr>',"\n";  
                }  
            }  
        }  
?>  
原文地址:https://www.cnblogs.com/lechie/p/2390197.html