PHP file to determine whether the method of picture

A method of using the getimagesize function retrieves the images, and then determines:

function isImage($filename)
{
    $types = '.gif|.jpeg|.png|.bmp';  //定义检查的图片类型
    if(file_exists($filename))
    {
        if (($info = @getimagesize($filename))
            return 0;

        $ext = image_type_to_extension($info['2']);
        return stripos($types,$ext);
    }
    else
    {
        return false;
    }
}

if(isImage('isimg.txt')!==false)
{
    echo isImage('1.jpg');
    echo '是图片';
}
else
{
    echo '不是图片';
}

The first 2 bytes of the image read method two, then the image is not determined:

function  isImg($fileName)
{
    $file     = fopen($fileName, "rb");
    $bin      = fread($file, 2);  // 只读2字节

    fclose($file);
    $strInfo  = @unpack("C2chars", $bin);
    $typeCode = intval($strInfo['chars1'].$strInfo['chars2']);
    $fileType = '';

    if($typeCode == 255216 /*jpg*/ || $typeCode == 7173 /*gif*/ || $typeCode == 13780 /*png*/)
    {
        return $typeCode;
    }
    else
    {
        // echo '"仅允许上传jpg/jpeg/gif/png格式的图片!';
        return false;
    }
}

if (isImg("1.jpg"))
{
    echo "是图片";
}
else
{
    echo "不是图片";
}

Method three
last method is the use of exif_imagetype function, the function for determining a type of an image, this method is more simple. The first byte of a read image and checks its signature. If you find a proper signature corresponding constant is returned, otherwise it returns FALSE. Return Value getimagesize () does the value of the index in the array returned 2 is the same, but the function is much faster. The return value of the function is constant is defined as follows:

1 IMAGETYPE_GIF
2 IMAGETYPE_JPEG
3 IMAGETYPE_PNG
4 IMAGETYPE_SWF
5 IMAGETYPE_PSD
6 IMAGETYPE_BMP
7 IMAGETYPE_TIFF_II(Intel 字节顺序)
8 IMAGETYPE_TIFF_MM(Motorola 字节顺序)
9 IMAGETYPE_JPC
10 IMAGETYPE_JP2
11 IMAGETYPE_JPX
12 IMAGETYPE_JB2
13 IMAGETYPE_SWC
14 IMAGETYPE_IFF
15 IMAGETYPE_WBMP
16 IMAGETYPE_XBM
示例:

$mimetype = exif_imagetype("1.jpg");
if ($mimetype == IMAGETYPE_GIF || $mimetype == IMAGETYPE_JPEG || $mimetype == IMAGETYPE_PNG || $mimetype == IMAGETYPE_BMP)
{
    echo "是图片";
}

 

Published 172 original articles · won praise 45 · views 40000 +

Guess you like

Origin blog.csdn.net/fish_study_csdn/article/details/102650583