PHP : binary image data, checking the image type

前端 未结 7 1569
刺人心
刺人心 2020-11-30 02:44

I have some images in bin, I want to check the header to check the format (jpg, png, etc)

I don\'t want to use temp files! I have a solution using TEMP FILES.

相关标签:
7条回答
  • 2020-11-30 03:06

    The bits start with:

    $JPEG = "\xFF\xD8\xFF"
    $GIF  = "GIF"
    $PNG  = "\x89\x50\x4e\x47\x0d\x0a\x1a\x0a"
    $BMP  = "BM"
    $PSD  = "8BPS"
    $SWF  = "FWS"
    

    The other ones I wouldn't know right now, but the big 3 (jpeg,gif,png) usually cover 99%. So, compare the first bytes to those string, and you have your answer.

    0 讨论(0)
  • 2020-11-30 03:17

    http://php.net/manual/en/function.getimagesize.php

    "Index 2 is one of the IMAGETYPE_XXX constants indicating the type of the image."

    0 讨论(0)
  • 2020-11-30 03:22

    Why not just check the file entension? :)

    An Alternative

    if(exif_imagetype($filepath) == IMAGETYPE_JPEG){
        echo 'This is a JPEG image';
    }
    
    0 讨论(0)
  • 2020-11-30 03:25

    Here's an implementation of the function as described by Wrikken

    function getImgType($filename) {
        $handle = @fopen($filename, 'r');
        if (!$handle)
            throw new Exception('File Open Error');
    
        $types = array('jpeg' => "\xFF\xD8\xFF", 'gif' => 'GIF', 'png' => "\x89\x50\x4e\x47\x0d\x0a", 'bmp' => 'BM', 'psd' => '8BPS', 'swf' => 'FWS');
        $bytes = fgets($handle, 8);
        $found = 'other';
    
        foreach ($types as $type => $header) {
            if (strpos($bytes, $header) === 0) {
                $found = $type;
                break;
            }
        }
        fclose($handle);
        return $found;
    }
    
    0 讨论(0)
  • 2020-11-30 03:31

    Use the fileinfo PHP extension:

    http://de.php.net/manual/en/function.finfo-file.php

    Its using the "file" *nix command to reliably determine the mime-type of a given file:

    $finfo = finfo_open(FILEINFO_MIME_TYPE); 
    $mimetype = finfo_file($finfo, $filename);
    finfo_close($finfo);
    

    This extension is shipped with PHP 5.3 or can be installed from pecl (pecl install fileinfo) for earlier versions.

    0 讨论(0)
  • 2020-11-30 03:32

    I can see that most of you didn't understand the question :) (question was how to validate binary data in buffer, not a file on disk).

    I had same problem, and resolved it with:

    $finfo = new finfo(FILEINFO_MIME_TYPE);
    $mimeType = $finfo->buffer($rawImage);
    
    0 讨论(0)
提交回复
热议问题