本文介绍了如何在php中获取图像类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取数据库中的图像类型,但以下内容不起作用.如何检测图像是png,jpeg还是gif?

I am trying to get the image type in the database but the below isn't working. How do I detect if the image is png, jpeg or 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>";
}

推荐答案

使用 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快得多.查看文档以获取更多信息.

Mind that exif_imagetype is much faster than getimagesize. Check documentation for more info.

这篇关于如何在php中获取图像类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-20 17:57