php图片格式转换

获取指定目录下的所有图片,然后将图片转换格式并且渐进式处理,需要注意透明png图片转换jpg图片背景变黑的问题。

所以需要分成两步操作:

  1. 遍历目录下的所有文件(包含子目录),得到所有图片
  2. 循环处理图片

关于png转换jpg背景变黑,可以在转换jpg之前,先创建一个白色的画布,然后将图像信息拷贝到这个白色画布上,就可以解决变黑的问题。

话不多说,直接上代码:

<?php
/**
* @param  $srcFile         source file
* @param  $dstFile         dest file
* @param  $towidth         new file width
* @param  $toheight         new file height
* @param  $type         the type of file conversion,when the value is default,the format will not be converted,only convert the picture to progressive
*/
function imageConvert($srcFile, $dstFile, $towidth, $toheight, $type="default") {
        $data = @getimagesize($srcFile);
        $createfun = str_replace("/", "createfrom", $data['mime']);

        $im = $createfun($srcFile);

        $srcW = @imagesx($im);
        $srcH = @imagesy($im);
        $dstW = $towidth;
        $dstH = $toheight;

        $imagefun = 'image'.$type;

        $file_ext = getExt($dstFile);
        if($type !== 'default') {
                if($file_ext !== $type) {
                        $dstFile = str_replace(".{$file_ext}", ".{$type}", $dstFile);
                }
                if ($type === 'jpg') {
                        $imagefun = 'imagejpeg';
                }
        }else {
                $imagefun = str_replace("/", "", $data['mime']);
        }

        echo "Converting '{$srcFile}' ----------> '{$dstFile}'<br>";

        $ni = @imagecreatetruecolor($dstW, $dstH);

        //png背景填色
        if($type === 'jpg') {
                if($data['mime'] === 'image/png') {
                        $white = imagecolorallocate($ni, 255, 255, 255);
                        imagefill($ni, 0, 0, $white);
                }
        }

        if(!empty($dstFile)) {
                $dir = substr($dstFile, 0, strripos($dstFile, "/"));
                if(!file_exists($dir)) {
                        mkdir($dir, 0777, true);
                }
        }else {
                die('Error:You must specify the value of $dstfile');
        }


        @imagecopyresampled($ni, $im, 0, 0, 0, 0, $dstW, $dstH, $srcW, $srcH);
        if($type === 'jpg' || $data['mime'] === 'image/jpeg') @imageinterlace($ni,1);        #picture progressive processing
        @$imagefun($ni,$dstFile);
        @imagedestroy($ni);
        @imagedestroy($im);
}

/**get all files
* @param  $path         file path
* @param  $files         file array
*/
function getAllFiles($path,&$files) {  
    if(is_dir($path)){  
        $dp = dir($path);
        while ($file = $dp ->read()){  
            if($file !="." && $file !=".."){  
                getAllFiles($path."/".$file, $files);  
            }  
        }  
        $dp ->close();  
    }  
    if(is_file($path)){  
        $files[] =  $path;  
    }  
}  

function getFileNamesByDir($dir){  
    $files =  array();  
    getAllFiles($dir,$files);  
    return $files;
}
#get the file extension
function getExt($filename) {
        if(!empty($filename)) {
                $tempArr = explode(".", $filename);
                return $tempArr[count($tempArr) - 1];
        }
}


#the directory to be converted
$src_dir = "./yourdirname";
#the directory where the files are saved after conversion
$dest_dir = "dest";
#need to processed image format
$imgExtArr = array("jpg","png");
$filenames = getFileNamesByDir($src_dir);
foreach ($filenames as $value) {
        ob_flush();
        flush();
     $file_ext = getExt($value);
     if(in_array($file_ext, $imgExtArr)) {
             if($imginfo = getimagesize($value)) {
                     list($src_w, $src_h) = $imginfo;
                     $srcFile = $value;
                     $dstFile = str_replace($src_dir, $dest_dir, $value);
                     imageConvert($srcFile, $dstFile, $src_w, $src_h, "jpg");
             }

     }
}
die("End of execution!");
如果您觉得本文对您有用,欢迎捐赠或留言~
微信支付
支付宝

发表评论

您的电子邮箱地址不会被公开。 必填项已用 * 标注