Create Image From Url Any File Type

后端 未结 7 1683
无人及你
无人及你 2020-12-02 17:25

I know of imagecreatefromgif(), imagecreatefromjpeg(), and imagecreatefrompng() but is there a way to create an image resource (for png preferably) from a url of any

7条回答
  •  萌比男神i
    2020-12-02 18:07

    Maybe you want this:

    $jpeg_image = imagecreatefromfile( 'photo.jpeg' );
    $gif_image = imagecreatefromfile( 'clipart.gif' );
    $png_image = imagecreatefromfile( 'transparent_checkerboard.PnG' );
    $another_jpeg = imagecreatefromfile( 'picture.JPG' );
    // This requires you to remove or rewrite file_exists check:
    $jpeg_image = imagecreatefromfile( 'http://example.net/photo.jpeg' );
    // SEE BELOW HO TO DO IT WHEN http:// ARGS IS NEEDED:
    $jpeg_image = imagecreatefromfile( 'http://example.net/photo.jpeg?foo=hello&bar=world' );
    

    Here's how it's done:

    function imagecreatefromfile( $filename ) {
        if (!file_exists($filename)) {
            throw new InvalidArgumentException('File "'.$filename.'" not found.');
        }
        switch ( strtolower( pathinfo( $filename, PATHINFO_EXTENSION ))) {
            case 'jpeg':
            case 'jpg':
                return imagecreatefromjpeg($filename);
            break;
    
            case 'png':
                return imagecreatefrompng($filename);
            break;
    
            case 'gif':
                return imagecreatefromgif($filename);
            break;
    
            default:
                throw new InvalidArgumentException('File "'.$filename.'" is not valid jpg, png or gif image.');
            break;
        }
    }
    

    With some small modifications to switch same function is ready for web url's:

        /* if (!file_exists($filename)) {
            throw new InvalidArgumentException('File "'.$filename.'" not found.');
        } <== This needs addiotional checks if using non local picture */
        switch ( strtolower( array_pop( explode('.', substr($filename, 0, strpos($filename, '?'))))) ) {
            case 'jpeg':
    

    After that you can use it with http://www.tld/image.jpg:

    $jpeg_image = imagecreatefromfile( 'http://example.net/photo.jpeg' );
    $gif_image = imagecreatefromfile( 'http://www.example.com/art.gif?param=23&another=yes' );
    

    Some proofs:

    As you can read from official PHP manual function.imagecreatefromjpeg.php GD allows loading images from URLs that is supported by function.fopen.php, so there is no need to fetch image first and save it to file, and open that file.

提交回复
热议问题