PHP 裁剪保留原透明度、原尺寸函数

PHP 裁剪保留原透明度、原尺寸函数
/**
 * 重置图片文件大小
 * @param  string $filePath 文件路径
 * @param  int $xmax     最大宽度
 * @param  int $ymax     最大高度
 * @return boolean       true/false
 */
ResetImageFileSize('C:\Users\Administrator\Desktop\0.46574.png',100,100);

function ResetImageFileSize($filePath, $xmax, $ymax)
{
    if(filesize($filePath) == 0) return 'error_file';
    //$extension = pathinfo($filePath)['extension'];
    $extension = explode('/',getimagesize($filePath)['mime'])[1];

    $img  = null;
    switch ($extension) {
        case 'jpg':
        case 'jpeg':
            $img = imagecreatefromjpeg($filePath);
            break;
        case 'png':
            $img = imagecreatefrompng($filePath);
            break;
        case 'gif':
            $img = imagecreatefromgif($filePath);
            break;
        case 'webp':
            $img = imagecreatefromwebp($filePath);
            break;
    }

    if(is_null($img)) return false;

    list($x,$y)  = getimagesize($filePath);

    if($x <= $xmax && $y <= $ymax){
        return true;
    }
    /*保留原宽高比率*/
    if($x >= $y) {
        $newX = ($x > $xmax) ? $xmax : $x;
        $newY = $newX * ($y / $x);
    }else{
        $newY = ($y > $ymax) ? $ymax : $y;
        $newX = ($x / $y) * $newY;
    }

    $img2 = imagecreatetruecolor($newX, $newY);
    imageantialias($img2,true);//使用抗锯齿
    if($extension == 'png'){
    $Color = imagecolorallocatealpha($img2, 0, 0, 0, 127);//设置透明
    }else{
        $Color = imagecolorallocate($img2,255,255,255);
    }
    imagecolortransparent($img2,$Color);
    imagefill($img2,0,0,$Color);

    if(function_exists('imagecopyresampled')){
        /*生成图像质量较好,但速度相比较慢*/
        imagecopyresampled($img2, $img, 0, 0, 0, 0, floor($newX), floor($newY), $x, $y);
    }else{
        /*生成图像质量较差,但速度相比较快*/
        imagecopyresized($img2, $img, 0, 0, 0, 0, floor($newX), floor($newY), $x, $y);
    }

    switch ($extension) {
        case 'jpg':
        case 'jpeg':
            imagejpeg($img2,$filePath,100);
            break;
        case 'png':
            imagesavealpha($img2,true);
            imagepng($img2,$filePath);
            //imagepng($img2,$filePath,9);
            break;
        case 'gif':
            imagegif($img2,$filePath);
            break;
        default:
            imagejpeg($img2,$filePath,100);
            break;
    }

    imagedestroy($img2);
    return true;
}

转载请注明出处 AE博客|墨渊 » PHP 裁剪保留原透明度、原尺寸函数

相关推荐

发表评论

路人甲

网友评论(0)