PHP:图片不变形处理(留白处理与截取处理)

此函数用于处理图片,变成缩略图,能使图片不变形,能选择两种模式,一是图片留白处理(放在画布中间),另一个是截取图片处理(从中间截取);

<?php
//将$filestring的图像文件变成等比不变形的缩略图($dstwidth*$dstheight)
//$type 用1表示留白方式处理,2表示截取方式处理
function getThumb($filestring,$dstwidth,$dstheight,$type)
{
    //0.局部变量声明
    $srcimg=0;
    $dstx=$dsty=$srcx=$srcy=0;
    $dstimg=imagecreatetruecolor($dstwidth,$dstheight);
    //1.得到$filestring里的文件类型(png,gif,jpeg,jpg)
    $yuan=getimagesize($filestring);
    $filetype=$yuan['mime'];
    switch($filetype)
    {
        case "image/png":$srcimg=imagecreatefrompng($filestring);break;
        case "image/jpg":
        case "image/jpeg":$srcimg=imagecreatefromjpeg($filestring);break;
        case "image/gif":$srcimg=imagecreatefromgif($filestring);break;
    }
    //2.得到原来文件的宽和高$src_w,$src_h
    $src_w=imagesx($srcimg);
    $src_h=imagesy($srcimg);
    //3.计算变形
    if($dstwidth/$dstheight < $src_w/$src_h)//传来的图像是横图
    {
        if($type==1)//用户需要留白处理
        {
            $dsty=(int)($dstheight-$src_h*$dstwidth/$src_w)/2;
            $dstheight=$dstheight-2*$dsty;
        }
        else//用户需要截取处理
        {
            $srcx=(int)($src_w-$dstwidth*$src_h/$dstheight)/2;
            $src_w=$src_w-2*$srcx;
        }
    }
    else  //传来的图像是竖图或等比的图
    {
        if($type==1)//用户需要留白处理
        {
            $dstx=(int)($dstwidth-$src_w*$dstheight/$src_h)/2;
            $dstwidth=$dstwidth-2*$dstx;
        }
        else//用户需要截取处理
        {
            $srcy=(int)($src_h-$dstheight*$src_w/$dstwidth)/2;
            $src_h=$src_h-2*$srcy;
        }       
    }
    //4.绘制缩略图
    imagecopyresampled($dstimg,$srcimg,$dstx,$dsty,$srcx,$srcy,$dstwidth,$dstheight,$src_w,$src_h);
    switch($filetype)
    {
        case "image/png":imagepng($dstimg,"img_thumb.jpg",9);break;
        case "image/jpg":
        case "image/jpeg":imagejpeg($dstimg,"img_thumb.jpg",100);break;
        case "image/gif":imagegif($dstimg,"img_thumb.jpg",100);break;
    }
    return $dstimg;

}
?>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章