web-dev-qa-db-fra.com

Créer une image à partir de l'URL de tout type de fichier

Je connais (imagecreatefromgif() } _, imagecreatefromjpeg() et imagecreatefrompng() , mais existe-t-il un moyen de créer une ressource image (pour png de préférence) à partir d'une URL de any type d'image valide? Ou devez-vous déterminer le type de fichier, puis utiliser la fonction appropriée?

Quand je dis URL, je veux dire quelque chose comme http://sample.com/image.png, pas une URL de données

14
Steve Robbins

Peut-être que vous voulez ceci:

$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' );

Voici comment c'est fait:

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;
    }
}

Avec quelques petites modifications à switch, la même fonction est prête pour les URL Web:

    /* 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':

Après cela, vous pouvez l'utiliser avec 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' );

Quelques preuves:

Comme vous pouvez le lire dans le manuel officiel PHP function.imagecreatefromjpeg.php Gd permet de charger des images à partir d'URL prises en charge par function.fopen.phppas besoin d'aller chercher l'image en premier et enregistrez-le dans un fichier et ouvrez ce fichier.

24
Sampo Sarrala

Le moyen le plus simple de le faire est de laisser php décider du type de fichier:

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

J'utilise cette fonction. Il supporte tous les types d'URL et les wrappers de flux et tous les types d'images que php peut gérer.

/**
 * 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;
  }
}

Utilisation (exemple simple): 

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

Utilisation (exemple complexe): 

// 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
6
Radon8472

Cela peut vous aider

$ image = imagecreatefromstring (file_get_contents ('votre chemin_image_ici'));

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

2
edCoder

Commencez par récupérer l'URL à l'aide de la fonction file_get_contents($url) et enregistrez le contenu dans un fichier. Après cela, vous pouvez utiliser les fonctions de manipulation d’image appropriées pour effectuer d’autres modifications. Vous pouvez utiliser le code suivant pour enregistrer l'image à partir de l'URL. Voici l exemple de code:

$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);

Merci.

1
Dev

vous analysez ce code.

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

Vous pourriez aussi être intéressé par la version la plus avancée: 

http://salman-w.blogspot.com/2008/10/resize-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;
}
?>
0
test30