Detecting image type from base64 string in PHP

前端 未结 7 1462
闹比i
闹比i 2020-11-27 14:32

Is it possible to find out the type of an image encoded as a base64 String in PHP?

I have no method of accessing the original image file, just the encoded string. F

7条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-27 14:54

    If you dont want to use these functions because of their dependencies you can use the first bytes of the data:

    function getBytesFromHexString($hexdata)
    {
      for($count = 0; $count < strlen($hexdata); $count+=2)
        $bytes[] = chr(hexdec(substr($hexdata, $count, 2)));
    
      return implode($bytes);
    }
    
    function getImageMimeType($imagedata)
    {
      $imagemimetypes = array( 
        "jpeg" => "FFD8", 
        "png" => "89504E470D0A1A0A", 
        "gif" => "474946",
        "bmp" => "424D", 
        "tiff" => "4949",
        "tiff" => "4D4D"
      );
    
      foreach ($imagemimetypes as $mime => $hexbytes)
      {
        $bytes = getBytesFromHexString($hexbytes);
        if (substr($imagedata, 0, strlen($bytes)) == $bytes)
          return $mime;
      }
    
      return NULL;
    }
    
    $encoded_string = "....";
    $imgdata = base64_decode($encoded_string);
    $mimetype = getImageMimeType($imgdata);
    

提交回复
热议问题