从Url创建图像任何文件类型

时间:2023-01-29 09:01:22

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 type of valid image? Or do you have to determine the file type and then use the appropriate function?

我知道imagecreatefromgif(),imagecreatefromjpeg()和imagecreatefrompng()但是有没有办法从任何类型的有效图像的url创建图像资源(最好是png)?或者你必须确定文件类型,然后使用适当的功能?

When I say url I mean something like http://sample.com/image.png, not a data url

当我说网址时,我的意思是http://sample.com/image.png,而不是数据网址

7 个解决方案

#1


23  

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:

之后,您可以将其与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.

正如您可以从官方PHP手册中看到的.imagecreatefromjpeg.php GD允许从function.fopen.php支持的URL加载图像,因此无需先获取图像并将其保存到文件中,然后打开该文件。

#2


22  

The simplest way to do this is let php decide what is the file type:

最简单的方法是让php决定文件类型是什么:

$image = imagecreatefromstring(file_get_contents($src));

#3


6  

I use this function. It supports all types of urls and stream wrappers and all image types php can handle.

我用这个功能。它支持所有类型的URL和流包装器以及php可以处理的所有图像类型。

/**
 * creates a image ressource from file (or url)
 *
 * @version: 1.1 (2014-05-02)
 *
 * $param string:    $filename                    url or local path to image file
 * @param [bool:     $use_include_path]           As of PHP 5 the FILE_USE_INCLUDE_PATH constant can be used to trigger include path search.
 * @param [resource: $context]                    A valid context resource created with stream_context_create(). If you don't need to use a custom context, you can skip this parameter by NULL
 * @param [&array:   $info]                       Array with result info: $info["image"] = imageinformation from getimagesize, $info["http"] = http_response_headers (if array was populated)
 *
 * @see: http://php.net/manual/function.file-get-contents.php
 * @see: http://php.net/manual/function.getimagesize.php
 *
 * @return bool|resource<gd>                       false, wenn aus Dateiinhalt keine gueltige PHP-Bildresource erstellt werden konnte (z.b. bei BMP-Datei)
 * @throws InvalidArgumentException                Wenn Datei kein gueltiges Bild ist, oder nicht gelesen werden kann
 *
 */
function createImageFromFile($filename, $use_include_path = false, $context = null, &$info = null)
{
  // try to detect image informations -> info is false if image was not readable or is no php supported image format (a  check for "is_readable" or fileextension is no longer needed)
  $info = array("image"=>getimagesize($filename));
  $info["image"] = getimagesize($filename);
  if($info["image"] === false) throw new InvalidArgumentException("\"".$filename."\" is not readable or no php supported format");
  else
  {
    // fetches fileconten from url and creates an image ressource by string data
    // if file is not readable or not supportet by imagecreate FALSE will be returnes as $imageRes
    $imageRes = imagecreatefromstring(file_get_contents($filename, $use_include_path, $context));
    // export $http_response_header to have this info outside of this function
    if(isset($http_response_header)) $info["http"] = $http_response_header;
    return $imageRes;
  }
}

Usage (simple example):

用法(简单示例):

$image = createImageFromFile("http://sample.com/image.png");

Usage (complex example):

用法(复杂的例子):

// even sources with php extensions are supported and e.g. Proxy connections and other context Options
// see http://php.net/manual/function.stream-context-create.php for examples
$options = array("http"=> 
                  array("proxy" => "tcp://myproxy:8080",
                        "request_fulluri" => true
                       )
                  );
$context = stream_context_create($options);

$image = createImageFromFile("http://de3.php.net/images/logo.php", null, $context,$info);

// ... your code to resize or modify the image

#4


2  

This may help you

这可能对你有所帮助

$image = imagecreatefromstring(file_get_contents('your_image_path_here'));

$ image = imagecreatefromstring(file_get_contents('your_image_path_here'));

Example: $image = imagecreatefromstring(file_get_contents('sample.jpg'));

示例:$ image = imagecreatefromstring(file_get_contents('sample.jpg'));

#5


1  

First fetch the url using file_get_contents($url) function and the save the content to a file. After that you can use proper image manipulation functions to further changes. You can use following code to save image from url. Here is the sample code:

首先使用file_get_contents($ url)函数获取url并将内容保存到文件中。之后,您可以使用正确的图像处理功能进一步更改。您可以使用以下代码从URL保存图像。以下是示例代码:

$url = "http://sample.com/image.png";
$arr = explode("/",$url);
$img_file = dir(__FILE__).'/'.$arr[count($arr)-1];
$data = file_get_contents($url);
$fp = fopen($img_file,"w");
fwrite($fp,$data);
fclose($fp);

Thanks.

#6


0  

you analyse this code.

你分析这段代码。

$url=$_SERVER['REQUEST_URI'];
$url=explode('.',$url);
$extension=$url[1];
switch($extension){
   case'jpg':
      imagecreatefromjpeg();
   break;
}

#7


0  

You might be also interested in most advanced version:

您可能也对*版本感兴趣:

http://salman-w.blogspot.com/2008/10/resize-images-using-phpgd-library.html

<?php
/*
 * PHP function to resize an image maintaining aspect ratio
 * http://salman-w.blogspot.com/2008/10/resize-images-using-phpgd-library.html
 *
 * Creates a resized (e.g. thumbnail, small, medium, large)
 * version of an image file and saves it as another file
 */

define('THUMBNAIL_IMAGE_MAX_WIDTH', 150);
define('THUMBNAIL_IMAGE_MAX_HEIGHT', 150);

function generate_image_thumbnail($source_image_path, $thumbnail_image_path)
{
    list($source_image_width, $source_image_height, $source_image_type) = getimagesize($source_image_path);
    switch ($source_image_type) {
        case IMAGETYPE_GIF:
            $source_gd_image = imagecreatefromgif($source_image_path);
            break;
        case IMAGETYPE_JPEG:
            $source_gd_image = imagecreatefromjpeg($source_image_path);
            break;
        case IMAGETYPE_PNG:
            $source_gd_image = imagecreatefrompng($source_image_path);
            break;
    }
    if ($source_gd_image === false) {
        return false;
    }
    $source_aspect_ratio = $source_image_width / $source_image_height;
    $thumbnail_aspect_ratio = THUMBNAIL_IMAGE_MAX_WIDTH / THUMBNAIL_IMAGE_MAX_HEIGHT;
    if ($source_image_width <= THUMBNAIL_IMAGE_MAX_WIDTH && $source_image_height <= THUMBNAIL_IMAGE_MAX_HEIGHT) {
        $thumbnail_image_width = $source_image_width;
        $thumbnail_image_height = $source_image_height;
    } elseif ($thumbnail_aspect_ratio > $source_aspect_ratio) {
        $thumbnail_image_width = (int) (THUMBNAIL_IMAGE_MAX_HEIGHT * $source_aspect_ratio);
        $thumbnail_image_height = THUMBNAIL_IMAGE_MAX_HEIGHT;
    } else {
        $thumbnail_image_width = THUMBNAIL_IMAGE_MAX_WIDTH;
        $thumbnail_image_height = (int) (THUMBNAIL_IMAGE_MAX_WIDTH / $source_aspect_ratio);
    }
    $thumbnail_gd_image = imagecreatetruecolor($thumbnail_image_width, $thumbnail_image_height);
    imagecopyresampled($thumbnail_gd_image, $source_gd_image, 0, 0, 0, 0, $thumbnail_image_width, $thumbnail_image_height, $source_image_width, $source_image_height);
    imagejpeg($thumbnail_gd_image, $thumbnail_image_path, 90);
    imagedestroy($source_gd_image);
    imagedestroy($thumbnail_gd_image);
    return true;
}
?>

#1


23  

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:

之后,您可以将其与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.

正如您可以从官方PHP手册中看到的.imagecreatefromjpeg.php GD允许从function.fopen.php支持的URL加载图像,因此无需先获取图像并将其保存到文件中,然后打开该文件。

#2


22  

The simplest way to do this is let php decide what is the file type:

最简单的方法是让php决定文件类型是什么:

$image = imagecreatefromstring(file_get_contents($src));

#3


6  

I use this function. It supports all types of urls and stream wrappers and all image types php can handle.

我用这个功能。它支持所有类型的URL和流包装器以及php可以处理的所有图像类型。

/**
 * creates a image ressource from file (or url)
 *
 * @version: 1.1 (2014-05-02)
 *
 * $param string:    $filename                    url or local path to image file
 * @param [bool:     $use_include_path]           As of PHP 5 the FILE_USE_INCLUDE_PATH constant can be used to trigger include path search.
 * @param [resource: $context]                    A valid context resource created with stream_context_create(). If you don't need to use a custom context, you can skip this parameter by NULL
 * @param [&array:   $info]                       Array with result info: $info["image"] = imageinformation from getimagesize, $info["http"] = http_response_headers (if array was populated)
 *
 * @see: http://php.net/manual/function.file-get-contents.php
 * @see: http://php.net/manual/function.getimagesize.php
 *
 * @return bool|resource<gd>                       false, wenn aus Dateiinhalt keine gueltige PHP-Bildresource erstellt werden konnte (z.b. bei BMP-Datei)
 * @throws InvalidArgumentException                Wenn Datei kein gueltiges Bild ist, oder nicht gelesen werden kann
 *
 */
function createImageFromFile($filename, $use_include_path = false, $context = null, &$info = null)
{
  // try to detect image informations -> info is false if image was not readable or is no php supported image format (a  check for "is_readable" or fileextension is no longer needed)
  $info = array("image"=>getimagesize($filename));
  $info["image"] = getimagesize($filename);
  if($info["image"] === false) throw new InvalidArgumentException("\"".$filename."\" is not readable or no php supported format");
  else
  {
    // fetches fileconten from url and creates an image ressource by string data
    // if file is not readable or not supportet by imagecreate FALSE will be returnes as $imageRes
    $imageRes = imagecreatefromstring(file_get_contents($filename, $use_include_path, $context));
    // export $http_response_header to have this info outside of this function
    if(isset($http_response_header)) $info["http"] = $http_response_header;
    return $imageRes;
  }
}

Usage (simple example):

用法(简单示例):

$image = createImageFromFile("http://sample.com/image.png");

Usage (complex example):

用法(复杂的例子):

// even sources with php extensions are supported and e.g. Proxy connections and other context Options
// see http://php.net/manual/function.stream-context-create.php for examples
$options = array("http"=> 
                  array("proxy" => "tcp://myproxy:8080",
                        "request_fulluri" => true
                       )
                  );
$context = stream_context_create($options);

$image = createImageFromFile("http://de3.php.net/images/logo.php", null, $context,$info);

// ... your code to resize or modify the image

#4


2  

This may help you

这可能对你有所帮助

$image = imagecreatefromstring(file_get_contents('your_image_path_here'));

$ image = imagecreatefromstring(file_get_contents('your_image_path_here'));

Example: $image = imagecreatefromstring(file_get_contents('sample.jpg'));

示例:$ image = imagecreatefromstring(file_get_contents('sample.jpg'));

#5


1  

First fetch the url using file_get_contents($url) function and the save the content to a file. After that you can use proper image manipulation functions to further changes. You can use following code to save image from url. Here is the sample code:

首先使用file_get_contents($ url)函数获取url并将内容保存到文件中。之后,您可以使用正确的图像处理功能进一步更改。您可以使用以下代码从URL保存图像。以下是示例代码:

$url = "http://sample.com/image.png";
$arr = explode("/",$url);
$img_file = dir(__FILE__).'/'.$arr[count($arr)-1];
$data = file_get_contents($url);
$fp = fopen($img_file,"w");
fwrite($fp,$data);
fclose($fp);

Thanks.

#6


0  

you analyse this code.

你分析这段代码。

$url=$_SERVER['REQUEST_URI'];
$url=explode('.',$url);
$extension=$url[1];
switch($extension){
   case'jpg':
      imagecreatefromjpeg();
   break;
}

#7


0  

You might be also interested in most advanced version:

您可能也对*版本感兴趣:

http://salman-w.blogspot.com/2008/10/resize-images-using-phpgd-library.html

<?php
/*
 * PHP function to resize an image maintaining aspect ratio
 * http://salman-w.blogspot.com/2008/10/resize-images-using-phpgd-library.html
 *
 * Creates a resized (e.g. thumbnail, small, medium, large)
 * version of an image file and saves it as another file
 */

define('THUMBNAIL_IMAGE_MAX_WIDTH', 150);
define('THUMBNAIL_IMAGE_MAX_HEIGHT', 150);

function generate_image_thumbnail($source_image_path, $thumbnail_image_path)
{
    list($source_image_width, $source_image_height, $source_image_type) = getimagesize($source_image_path);
    switch ($source_image_type) {
        case IMAGETYPE_GIF:
            $source_gd_image = imagecreatefromgif($source_image_path);
            break;
        case IMAGETYPE_JPEG:
            $source_gd_image = imagecreatefromjpeg($source_image_path);
            break;
        case IMAGETYPE_PNG:
            $source_gd_image = imagecreatefrompng($source_image_path);
            break;
    }
    if ($source_gd_image === false) {
        return false;
    }
    $source_aspect_ratio = $source_image_width / $source_image_height;
    $thumbnail_aspect_ratio = THUMBNAIL_IMAGE_MAX_WIDTH / THUMBNAIL_IMAGE_MAX_HEIGHT;
    if ($source_image_width <= THUMBNAIL_IMAGE_MAX_WIDTH && $source_image_height <= THUMBNAIL_IMAGE_MAX_HEIGHT) {
        $thumbnail_image_width = $source_image_width;
        $thumbnail_image_height = $source_image_height;
    } elseif ($thumbnail_aspect_ratio > $source_aspect_ratio) {
        $thumbnail_image_width = (int) (THUMBNAIL_IMAGE_MAX_HEIGHT * $source_aspect_ratio);
        $thumbnail_image_height = THUMBNAIL_IMAGE_MAX_HEIGHT;
    } else {
        $thumbnail_image_width = THUMBNAIL_IMAGE_MAX_WIDTH;
        $thumbnail_image_height = (int) (THUMBNAIL_IMAGE_MAX_WIDTH / $source_aspect_ratio);
    }
    $thumbnail_gd_image = imagecreatetruecolor($thumbnail_image_width, $thumbnail_image_height);
    imagecopyresampled($thumbnail_gd_image, $source_gd_image, 0, 0, 0, 0, $thumbnail_image_width, $thumbnail_image_height, $source_image_width, $source_image_height);
    imagejpeg($thumbnail_gd_image, $thumbnail_image_path, 90);
    imagedestroy($source_gd_image);
    imagedestroy($thumbnail_gd_image);
    return true;
}
?>