现在的位置: 首页 > 综合 > 正文

PHP 批量修改文件后缀名

2017年12月26日 ⁄ 综合 ⁄ 共 1475字 ⁄ 字号 评论关闭

最近在看外包公司给做的cms网站,但是发现在本地配置好后,一直刷新首页,apache会挂掉,觉得奇怪,于是进程序查看,发现首页所有的图片都是动态读取的,在本地保存的形式是“.dat”的格式,没访问一次首页,所有的图片都会从“.dat”文件读取一次数据,然后通过程序生成图片,真TMD蛋疼,是谁这样做的,难道做成静态的图片不好吗?于是我写了一个小小的php代码来实现这个功能,即将现有的“.dat”文件批量生成新文件夹中对应的图片文件,代码如下:

<?php
/**
 *@desc 将$origDir文件夹里的所有文件转化为$newDir文件夹中后缀名为.$newExt的文件
 *@author yuanj
 *@param string $origDir
 *@param string $newDir
 *@return void
 *@date 2013-3-27
 */
function fileTransfer($origDir,$newDir,$newExt='jpg'){
    if (!is_dir($origDir) or !is_dir($newDir)) {
        return;
    }
    $origDirArray = scandir($origDir);
    foreach ($origDirArray as $v) {
        if ($v == '.' or $v == '..') {//若为文件夹则跳过
            continue;
        }
        $orig_file = $origDir.'/'.$v;
        $new_location = $newDir.'/'.$v;
        if (is_dir($orig_file)) {
            if (!file_exists($new_location)) {
                mkdir($new_location,0700);//创建新文件夹
            }
            fileTransfer($origDir.'/'.$v,$newDir.'/'.$v,$newExt);
            continue;
        }
        if (file_exists($orig_file)){
            $newFileName = dirname($orig_file);
            $newFileName = str_replace($newFileName, '', $orig_file);
            $origExt = pathinfo($orig_file,PATHINFO_EXTENSION);
            $newFileName = str_replace($origExt, $newExt, $newFileName);
            $newFileName = $newDir.$newFileName;
            $fileData = file_get_contents($orig_file);
            $newFile = fopen($newFileName, 'a');
            fwrite($newFile, $fileData);
            fclose($newFile);
            echo '<br>',$orig_file,' ---> ',$newFileName;
            ob_flush();
            flush();
            sleep(1);
        }   
    }
}

$origDir = 'C:/AppServ/www/intra/uploads';
$newDir = 'C:/AppServ/www/intra/images';
echo 'start transfer,please wait ^V^';
fileTransfer($origDir,$newDir,'png');
echo '<br>transfer finished';


源码地址:http://download.csdn.net/detail/simpleiseasy/5196707

运行效果如下:


转换前文件为:


转换后的图片为:

抱歉!评论已关闭.