如何在php中获取图像类型

时间:2011-10-28 06:41:58

标签: php

我正在尝试在数据库中获取图像类型,但以下内容无效。如何检测图像是png,jpeg还是gif?

if(isset($_POST['submit'])) {
    $fileType = $_FILES['image']['type'];
    $tmpname = $_FILES['image']['tmp_name'];
    $fp = fopen($tmpname,'r');
    $data = fread($fp,filesize($tmpname));
    $data = addslashes($data);
    fclose($fp);

    $update = mysql_query("UPDATE avatar SET image1='$data',type='$fileType' WHERE username='$user'",$this->connect);
} else {
    echo "<form enctype='multipart/form-data' action='http://www.example.com/cp/avatar' method='post'>
        <div id='afield1' >Upload</div><div id='afield2'><input type='hidden' name='MAX_FILE_SIZE' value='102400' /><input type='file' size='25' name='image' /></div>
        <div id='asubmit'><input type='submit' name='submit' class='button' value='Save Changes' /></div>
        </form>";
}

1 个答案:

答案 0 :(得分:18)

使用getimagesize()exif_imagetype()

// integer - for example: IMAGETYPE_GIF, IMAGETYPE_JPEG etc.
$type   = exif_imagetype($_FILES['image']['tmp_name']);

$info   = getimagesize($_FILES['image']['tmp_name']);
$mime   = $info['mime']; // mime-type as string for ex. "image/jpeg" etc.
$width  = $info[0];      // width as integer for ex. 512
$height = $info[1];      // height as integer for ex. 384
$type   = $info[2];      // same as exif_imagetype

请注意exif_imagetypegetimagesize快得多。查看文档以获取更多信息。