Detecting image type from base64 string in PHP

前端 未结 7 1343
闹比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:40

    Code below will get the image type from its mime type.

    <?php 
    $base64 = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAKIAAAAxCAYAAABZAHL2AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAgfSURBVHhe7ZwxTBVLFIaH916wACstoDChEENhIxWYoJUmSqeJWkmiNkQS6TBBzSskUStNoNOCYCOJUKmJoVETY6WVjdJrow1UUvDyjfe/OYy7e+/ivbLknS/Z7N3ZndkzZ/45c3ZZ7RgeHt4MjrPD/FXbO86O4kJ0KoEL0akELkSnErgQnUrgQnQqQVuFODo6Go4dO1Y7cpx82ibEycnJMD09HW7cuBF6e3trpY6TTduEuLa2Fvfd3d3hzp078bfj5PH3gQMH/q39bikfPnwIg4ODMRru27cv7N27N7x796521nG20tKImOaDU1NTYX19Pf4+d+6c54tOLi2LiOSC4+PjoaenJ7x58yaW/fjxI3z8+DGcPn06Hg8NDYWVlZW6OB1HtCQisgQr2vGkPDs7G3NDeP/+fXj06FH87fmik0dLIuKXL19i/nfixInQ2dkZ80KiH9Hw+/fvni86DWlZjvj58+dw5syZuIf+/v4wNzcXBQieLzpFtPSpmZyQHJCohxCJjuSHX79+jdExzReXl5djnSpB1MZ2bHb+HNuOiOR7T58+DZcvX97ywpqod/v27XpeCLzYZtsN+SIThUi+m2G1IU9/+fJlePv2bSyjT/zWcdXYthB5KEGACBFBIjQrSAQ3MzNTX471EPPkyZOYMxJxHjx4EM+VhXZoz/kVRMgEJyXSA+NuYNtCRGB2+UIYEqTywmfPnoWrV6/WxUg5MxORXrx4sZ5PloV2eE3k/Mr58+drv0K4fv16mJiYqB1Vm20LEZHxcELUSwVJxGJDMOlDDFHz06dPdXE67eP169cxHdoN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qntmwansymy2NCPcWwYg3MxmuMy7/wwXnmfYOAQ882bN7csG4J7IFSlANYBPLUWCTgP5Y30lVdRLOvpki40KCkSKHvyL6IG0T5LoII+qN6fJM9HsoXoho9BD1kIEAHTD1YwNvkiq29FbPs9YhYYjUARJ4Igb+GBIX1dUBY6hSi0HKRoYJVvWayDmaV5oknRwwv9oV2iU1pX97LRyi5P1hYbUYSErbcDQB38l7W1g2b7wF4PT+lEkq9s39ouRLu0ltmaheiXNTtxjJYAnGKXMznLOgI4tmXKP7U0CpbDtK5FD1qKBELORqB6ULN/P7eDwWDJTmBSKNpQrlwL+zThaJcopEj0O9h70w9shTJ9SPNrnSMqamyA47JRvaUR8XdBgCzBS0tLdaew8UROXqKogKBYBnAo5TiIgeSYZZSBY09+aUEM1KVt63SuR4x5MIjkxDa/AwSq3Ipy2lNOR7kihbCDih0WpRT4gHSCyUu/sYtN7W4Xm1aQZmArlOmDtR9brTDtOfu7WQo/A5OxIBHYsjJk1U+XGz4Jo+PMrj179oTDhw/HckRGzqaO81EtjuBVEh/e4jA6z+/9+/fHz9B423/v3r3A+0vK9SEu13E9EYD6Gxsb4fHjx2FhYSGe53pmsyKUoA735LwGzn72Rnt89obt3OPWrVvxegvt9vX1xWsePny45RM42Ui/1RZgB5NA9mMz9WgjFTPknbd9wi6dL9MHfnMNe+pYH3379q3eN0RPf8pQ+JcVu6T+bp4n2tGms/up1NLs/H9pOiK2A4+IjvCI6FQCF6JTCfw/c3cqgUdEpxK4EJ1K4EJ0KoEL0akELkSnErgQnUrgQnQqgQvRqQQuRKcSdPT39/tfVpwdp2NgYMCF6OwwIfwHN+rCnrjztp8AAAAASUVORK5CYII=";
    
    $image_info = getimagesize($base64);
    
    $extension = (isset($image_info["mime"]) ? explode('/', $image_info["mime"] )[1]: "");
    
    echo $extension;
     
    ?>
    
    0 讨论(0)
  • 2020-11-27 14:48

    If you know a minimal amount about the file format structure, you could theoretically look at the top bytes of the file until you could work out what type of file it is.

    For example, a GIF image always starts with the following bytes GIF89a. If you can find that string at the begining of the file, you can be reasonably sure that it is a GIF image and absolutely certain it isn't any other image format. (it could still be a text file though, that just happens to start with 'GIF89a'; you'd have to parse more of the file to be absolutely certain)

    Likewise, PNG files have the string PNG fairly near the start (it's not quite at the very begining; again, you'd need to research the file format specifics to help you determine how much you'd need to know to be certain).

    JPEGs also contain recognisable strings in their headers, although these are more varied and complex. You might want to look out for the string Exif.

    Getting the file format definitions would definitely give you more accuracy, but depending on how accurate you need to be, you might learn enough about the files formats just by opening some image files in a binary editor to see how they're structured.

    These resources may help you:

    • http://www.w3.org/Graphics/JPEG/

    • http://www.w3.org/Graphics/PNG/

    0 讨论(0)
  • 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);
    
    0 讨论(0)
  • 2020-11-27 14:58

    Follow PHP.NET Fileinfo :-

    $finfo = finfo_open(FILEINFO_MIME_TYPE); // return mime type ala mimetype extension
    foreach (glob("*") as $filename) {
    echo finfo_file($finfo, $filename) . "\n";
    }
    finfo_close($finfo);
    
    0 讨论(0)
  • 2020-11-27 14:59

    The solution given by @Marc B is the best one for me (if our php version is > 5.3.0 otherwise we can use the solution given by @Aaron Murgatroyd).

    I would like to give a little addition to this solution.

    To get the image type you can do it like this :

    $split = explode( '/', $mime_type );
    $type = $split[1]; 
    

    In fact, (if you don't know it) the mime type for images is : image/type and type can be png or gif or jpeg or ...

    Hope that can help someone and thanks to @Marc B for his solution.

    For an exhaustive list of mime type you can look here :

    • http://www.sitepoint.com/web-foundations/mime-types-complete-list/
    0 讨论(0)
  • 2020-11-27 15:02

    FileInfo can do that for you:

    $encoded_string = "....";
    $imgdata = base64_decode($encoded_string);
    
    $f = finfo_open();
    
    $mime_type = finfo_buffer($f, $imgdata, FILEINFO_MIME_TYPE);
    
    0 讨论(0)
提交回复
热议问题