一个技术宅的个人博客

php获取图片格式(图片后缀)

getimagesize(真实格式,支持base64)

代码:

<?php
/*
@desc:获取图片真实后缀
@param   name    文件名
@return  suffix  文件后缀
*/   
function getimgsuffix($name) {
    $info = getimagesize($name);
    $suffix = false;
    if($mime = $info['mime']){
        $suffix = explode('/',$mime)[1];
    }
    return $suffix;
}

测试:

$suffix = getimgsuffix('http://192.168.8.81/public/image/01.jpg');
echo $suffix;

输出:

jpg

二进制方法(真实格式)

代码:

<?php
/*
@desc:获取文件真实后缀
@param   name    文件名
@return  suffix  文件后缀
*/   
function getfilesuffix($name) {
    $file = fopen($name, "rb");
    $bin = fread($file, 2); // 只读2字节
    fclose($file);
    $info = @unpack("C2chars", $bin);
    $code = intval($info['chars1'] . $info['chars2']);
    $suffix = "unknow";
    if($code == 255216){
        $suffix = "jpg";
    }elseif($code == 7173){
        $suffix = "gif";
    }elseif($code == 13780){
        $suffix = "png";
    }elseif($code == 6677){
        $suffix = "bmp";
    }elseif($code == 7798){
        $suffix = "exe";
    }elseif($code == 7784){
        $suffix = "midi";
    }elseif($code == 8297){
        $suffix = "rar";
    }elseif($code == 7368){
        $suffix = "mp3";
    }elseif($code == 0){
        $suffix = "mp4";
    }elseif($code == 8273){
        $suffix = "wav";
    }
    return $suffix;
}

测试:

$suffix = getfilesuffix('http://192.168.8.81/public/image/01.jpg');
echo $suffix;

输出:

jpg

strrchr strrpos substr

<?php
    $filename = "phpddt.jpg";
    echo substr(strrchr($filename,"."),1);
?>

<?php
    $filename = "phpddt.jpg";
    echo substr($filename,strrpos($filename,".")+1);
?>

explode array_pop

<?php
    $filename = "phpddt.jpg";
    $arr = explode(".",$filename);
    echo array_pop($arr);
?>

pathinfo

<?php
    $filename = "phpddt.jpg";
    $info = pathinfo($filename);
    echo $info['extension'];
?>

<?php
    $filename = "phpddt.jpg";
    echo pathinfo($filename,PATHINFO_EXTENSION);
?>
赞(7) 打赏
未经允许不得转载:孙健个人博客 » php获取图片格式(图片后缀)

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏