ImageCreateFromString and getimagesize in PHP

前端 未结 4 574
我寻月下人不归
我寻月下人不归 2021-02-10 22:36

Currently if a user POST/uploads a photo to my PHP script I start out with some code like this

getimagesize($_FILES[\'picture1\'][\'tmp_name\']);
4条回答
  •  [愿得一人]
    2021-02-10 23:30

    I suggest you follow this approach:

    // if you need the image type
    $type = exif_imagetype($url);
    
    // if you need the image mime type
    $type = image_type_to_mime_type(exif_imagetype($url));
    
    // if you need the image extension associated with the mime type
    $type = image_type_to_extension(exif_imagetype($url));
    
    // if you don't care about the image type ignore all the above code
    $image = ImageCreateFromString(file_get_contents($url));
    
    echo ImageSX($image); // width
    echo ImageSY($image); // height
    

    Using exif_imagetype() is a lot faster than getimagesize(), the same goes for ImageSX() / ImageSY(), plus they don't return arrays and can also return the correct image dimension after the image has been resized or cropped for instance.

    Also, using getimagesize() on URLs isn't good because it'll consume much more bandwidth than the alternative exif_imagetype(), from the PHP Manual:

    When a correct signature is found, the appropriate constant value will be returned otherwise the return value is FALSE. The return value is the same value that getimagesize() returns in index 2 but exif_imagetype() is much faster.

    That's because exif_imagetype() will only read the first few bytes of data.

提交回复
热议问题