20
00:27:01 00:27:01 Programmation Web 2011-2012 Programmation Web 2011-2012 1 PHP PHP Création et Création et manipulation d'images manipulation d'images Jérôme CUTRONA Jérôme CUTRONA [email protected] [email protected]

PHP Création et manipulation d'images

  • Upload
    jolie

  • View
    54

  • Download
    0

Embed Size (px)

DESCRIPTION

PHP Création et manipulation d'images. Jérôme CUTRONA [email protected]. Préambule. L'utilisation habituelle de PHP consiste à produire des pages HTML. - PowerPoint PPT Presentation

Citation preview

Page 1: PHP Création et manipulation d'images

19:25:1819:25:18 Programmation Web 2011-2012Programmation Web 2011-2012 11

PHPPHPCréation et manipulation Création et manipulation

d'imagesd'imagesJérôme CUTRONAJérôme CUTRONA

[email protected]@univ-reims.fr

Page 2: PHP Création et manipulation d'images

2219:25:1819:25:18 Programmation Web 2011-2012Programmation Web 2011-2012

PréambulePréambule

L'utilisation habituelle de PHP consiste à produire des L'utilisation habituelle de PHP consiste à produire des pages HTML.pages HTML.

Grâce à la Grâce à la bibliothèquebibliothèque GDGD, PHP peut produire des , PHP peut produire des images enregistrées sur disque ou directement images enregistrées sur disque ou directement transmises au navigateur du client.transmises au navigateur du client.

Formats d'images accessibles sont Formats d'images accessibles sont GIFGIF, , JPEGJPEG et et PNGPNG

Possibilités offertes par la création/manipulation Possibilités offertes par la création/manipulation d'images en PHP :d'images en PHP :

redimensionnement à la voléeredimensionnement à la volée CAPTCHA (CAPTCHA (Completely Automated Public Turing test to tell Completely Automated Public Turing test to tell

Computers and Humans ApartComputers and Humans Apart)) insertion de texte dynamiqueinsertion de texte dynamique

Page 3: PHP Création et manipulation d'images

3319:25:1819:25:18 Programmation Web 2011-2012Programmation Web 2011-2012

Algorithme général de créationAlgorithme général de création

Création d'une image :Création d'une image : nouvellenouvelle à partir d'un fichierà partir d'un fichier

Manipulations de l'imageManipulations de l'image dessindessin textetexte ……

Production de l'image finale :Production de l'image finale : dans un fichierdans un fichier envoi vers le navigateurenvoi vers le navigateur

Libération mémoireLibération mémoire

Page 4: PHP Création et manipulation d'images

4419:25:1819:25:18 Programmation Web 2011-2012Programmation Web 2011-2012

Algorithme général de créationAlgorithme général de création

<?php<?php// Création// Création$$imim == imageCreateTrueColorimageCreateTrueColor((100100, , 100100)) ;;

// Manipulations// Manipulations$$redred == imageColorAllocateimageColorAllocate(($$imim, , 255255, , 00, , 00)) ;;imageFilledRectangleimageFilledRectangle(($$imim, , 00, , 00,, 9999, , 9999, , $$redred)) ;;

// Envoi vers le navigateur// Envoi vers le navigateurheaderheader((''Content-Type: image/pngContent-Type: image/png'')) ;;imagePNGimagePNG(($$imim)) ;;

// Libération mémoire// Libération mémoireimageDestroyimageDestroy(($$imim)) ;;

Page 5: PHP Création et manipulation d'images

5519:25:1819:25:18 Programmation Web 2011-2012Programmation Web 2011-2012

Création d'une image (vide)Création d'une image (vide)

resource resource imageCreateimageCreate ( int ( int widthwidth, int , int heightheight ) )

construit une image vide de largeur construit une image vide de largeur widthwidth et de hauteur et de hauteur heightheight et retourne son identifiant.et retourne son identifiant.L'image est à couleurs indexées.L'image est à couleurs indexées.Retourne Retourne falsefalse en cas d'échec. en cas d'échec.

resource resource imageCreateTrueColorimageCreateTrueColor ( int ( int widthwidth, int , int heightheight ) )

construit une image vide de largeur construit une image vide de largeur widthwidth et de hauteur et de hauteur heightheight et retourne son identifiant.et retourne son identifiant.L'image est à couleurs "réelles" (24bits).L'image est à couleurs "réelles" (24bits).Retourne Retourne falsefalse en cas d'échec. en cas d'échec.

bool bool imageDestroyimageDestroy ( resource ( resource imageimage ) )

libère la mémoire associée à libère la mémoire associée à imageimage

Page 6: PHP Création et manipulation d'images

6619:25:1819:25:18 Programmation Web 2011-2012Programmation Web 2011-2012

Création d'une image (fichier)Création d'une image (fichier)

resource resource imageCreateFromGIFimageCreateFromGIF ( string ( string nomnom ) )

construit une image à partir du fichier GIF construit une image à partir du fichier GIF nomnom

resource resource imageCreateFromJPEGimageCreateFromJPEG ( string ( string nomnom ) )

construit une image à partir du fichier JPEG construit une image à partir du fichier JPEG nomnom

resource resource imageCreateFromPNGimageCreateFromPNG ( string ( string nomnom ) )

construit une image à partir du fichier PNG construit une image à partir du fichier PNG nomnom

resource resource imageCreateFromGD[2]imageCreateFromGD[2] ( string ( string nomnom ) )

construit une image à partir du fichier GD[2] construit une image à partir du fichier GD[2] nomnom

Page 7: PHP Création et manipulation d'images

7719:25:1819:25:18 Programmation Web 2011-2012Programmation Web 2011-2012

Production d'une imageProduction d'une image

bool bool imageGIFimageGIF (resource (resource imageimage [, string [, string fnamefname])])

construit un fichier GIF construit un fichier GIF fnamefname à partir de à partir de imageimage

bool bool imageJPEGimageJPEG (resource (resource imageimage [, string [, string fnamefname])])

construit un fichier JPEG construit un fichier JPEG fnamefname à partir de à partir de imageimage

bool bool imagePNGimagePNG (resource (resource imageimage [, string [, string fnamefname])])

construit un fichier PNG construit un fichier PNG fnamefname à partir de à partir de imageimage

bool bool imageGD[2]imageGD[2] (resource (resource imageimage [, string [, string fnamefname])])

construit un fichier GD[2] construit un fichier GD[2] fnamefname à partir de à partir de imageimage

Si Si fnamefname est absent, le contenu est transmis est absent, le contenu est transmis

Page 8: PHP Création et manipulation d'images

8819:25:1919:25:19 Programmation Web 2011-2012Programmation Web 2011-2012

Allocation de couleursAllocation de couleurs

int int imageColorAllocateimageColorAllocate ( resource ( resource imim,,

intint RR, int , int GG, int , int BB ))

construit une couleur (construit une couleur (RR, , GG, , BB) pour l'image ) pour l'image imim et et retourne son identifiant.retourne son identifiant. 0 0 ≤≤ RR ≤ 255≤ 255 0 0 ≤≤ GG ≤ 255≤ 255 0 0 ≤≤ BB ≤ 255≤ 255

Page 9: PHP Création et manipulation d'images

9919:25:1919:25:19 Programmation Web 2011-2012Programmation Web 2011-2012

Allocation de couleursAllocation de couleurs

int int imageColorAllocateAlphaimageColorAllocateAlpha ( resource ( resource imim,,

int int RR, int , int GG, int , int BB,,

int int AA ))

construit une couleur (construit une couleur (RR, , GG, , BB, , AA) pour l'image ) pour l'image imim et retourne son identifiant.et retourne son identifiant.0 0 ≤≤ RR ≤ 255≤ 2550 0 ≤≤ GG ≤ 255≤ 2550 0 ≤≤ BB ≤ 255≤ 2550 0 ≤≤ AA ≤ 127 (transparence de la couleur)≤ 127 (transparence de la couleur)

Page 10: PHP Création et manipulation d'images

101019:25:1919:25:19 Programmation Web 2011-2012Programmation Web 2011-2012

Copie redimensionnée d'imagesCopie redimensionnée d'images

bool bool imageCopyResizedimageCopyResized ( (resource resource dst_imdst_im, resource , resource src_imsrc_im,,intint dst_xdst_x,, intint dst_ydst_y, int , int src_xsrc_x, int , int src_ysrc_y,,int int dst_wdst_w, int , int dst_hdst_h, int , int src_wsrc_w, int , int src_hsrc_h ))

copie une portion rectangulaire de copie une portion rectangulaire de src_imsrc_im dans dans une portion rectangulaire une portion rectangulaire dst_imdst_im. Si les portions . Si les portions sont de taille différente, l'approximation se fait à sont de taille différente, l'approximation se fait à l'échantillon le plus proche.l'échantillon le plus proche.

bool bool imageCopyResampledimageCopyResampled ( … ) ( … ) remplace remplace l'approximation par un ré-échantillonnagel'approximation par un ré-échantillonnage

Page 11: PHP Création et manipulation d'images

111119:25:1919:25:19 Programmation Web 2011-2012Programmation Web 2011-2012

Dessiner dans une imageDessiner dans une image

int int imageColorAllocateimageColorAllocate ( resource ( resource imageimage,,int int redred, int , int greengreen, int , int blueblue ))

bool bool imageArc imageArc ( resource ( resource imageimage,, int int cxcx, int , int cycy,, int int widthwidth, int , int heightheight,, intint startstart, int , int endend, int , int colorcolor ))

bool bool imageLineimageLine ( resource ( resource imageimage,, int int x1x1, int , int y1y1,, int int x2x2, int , int y2y2, int , int colorcolor ))

bool bool imageStringimageString ( resource ( resource imageimage, int , int fontfont,, int int xx, int , int yy, string , string ss, int , int colorcolor ))

Page 12: PHP Création et manipulation d'images

121219:25:1919:25:19 Programmation Web 2011-2012Programmation Web 2011-2012

Création d'images à la voléeCréation d'images à la volée

<<imgimg  srcsrc=="img.php""img.php"

altalt=="Mon image""Mon image"

heightheight=="152""152"  widthwidth=="210""210">><?php<?php// Création// Création$$imim == imageCreateimageCreate((100100, , 100100)) ;;

// Manipulations// Manipulations$$redred = = imageColorAllocateimageColorAllocate(($$imim,, 255255, , 00, , 00)) ;;imageFilledRectangleimageFilledRectangle(($$imim, , 00, , 00,, 9999, , 9999, , $$redred)) ;;

// Envoi vers le navigateur// Envoi vers le navigateurheaderheader((''Content-Type: image/pngContent-Type: image/png'')) ;;imagePNGimagePNG(($$imim)) ;;

// Libération mémoire// Libération mémoireimageDestroyimageDestroy(($$imim)) ;;

Peut dépendre de paramètres Peut dépendre de paramètres GET :GET :

•img.php?t=Coucouimg.php?t=Coucou•img.php?r=10&v=120&b=255img.php?r=10&v=120&b=255•img.php?i=im.jpgimg.php?i=im.jpg•……

Page 13: PHP Création et manipulation d'images

Introduction d’une vision objet ?Introduction d’une vision objet ?

resource resource imageCreateTrueColorimageCreateTrueColor ( int ( int widthwidth, int , int heightheight ) )

int int imageColorAllocateimageColorAllocate ( resource ( resource imageimage, …, … bool bool imageArc imageArc ( resource ( resource imageimage, …, … bool bool imageLineimageLine ( resource ( resource imageimage, …, … bool bool imageStringimageString ( resource ( resource imageimage, …, …

bool bool imageDestroyimageDestroy ( resource ( resource imageimage ) )

131319:25:1919:25:19 Programmation Web 2011-2012Programmation Web 2011-2012

resource

resource représente l’

représente l’e

ntité im

age

entité im

age manipulée

manipulée

Page 14: PHP Création et manipulation d'images

Encapsulation objetEncapsulation objet

class GDImage class GDImage {{

// @var resource $_resource image identifier// @var resource $_resource image identifier

        private private $$_resource _resource = = null ;null ;

        private private function function __construct__construct() {() {

        }}

        public public function function __destruct__destruct() {() {

                if if ((!!is_nullis_null(($$thisthis->_resource->_resource))))

                        imageDestroyimageDestroy(($$thisthis->_resource->_resource) ;) ;

        }}

141419:25:1919:25:19 Programmation Web 2011-2012Programmation Web 2011-2012

Page 15: PHP Création et manipulation d'images

Encapsulation objet : usineEncapsulation objet : usine

public static public static functionfunction

createFromSizecreateFromSize(($$x, x, $$y, y, $$truecolortruecolor==truetrue) {) {

        $$x x = = ((intint) ) $$x ; x ; $$y y = = ((intint) ) $$y ;y ;

        $$resource resource = = false ;false ;

        if if (($$truecolortruecolor))

                  $$resource resource = @= @imageCreateTrueColorimageCreateTrueColor(($$x, x, $$yy) ;) ;

        else $else $resource resource = @= @imageCreateimageCreate(($$x, x, $$yy) ;) ;

        if if (($$resource resource !== !== falsefalse) {) {

                $$image image = = new new selfself() ;() ;

                $$imageimage->_resource ->_resource = $= $resource ;resource ;

                return $return $image ; image ; }}

        elseelse

                throw throw new new LogicExceptionLogicException("("Failed to create Failed to create GD resource"GD resource") ; ) ; }}

151519:25:1919:25:19 Programmation Web 2011-2012Programmation Web 2011-2012

Page 16: PHP Création et manipulation d'images

Encapsulation objet : usineEncapsulation objet : usine

public static public static functionfunction

createFromFilecreateFromFile(($$filename, filename, $$filetypefiletype) {) {

    if if ((is_fileis_file(($$filenamefilename)) {)) {

          if if ((in_arrayin_array(($$filetype, filetype, selfself::$::$_factory_types_factory_types))))

{{

                $$functionName functionName = '= 'imageCreateFrom' imageCreateFrom' . $. $filetype ;filetype ;

                $$image image = = new new selfself() ;() ;

                if if (((($$tmp tmp = @$= @$functionNamefunctionName(($$filenamefilename))))

   === === falsefalse) {) {

                        throw throw new new ExceptionException("("unable to load file unable to load file ''{{$$filenamefilename}}'"'") ;) ;

                }}

                $$imageimage->_resource ->_resource = $= $tmp ; tmp ; return $return $image ;image ;

          } } else else throw throw new new ExceptionException("("unknown filetype"unknown filetype") ;) ;

    } } else else throw throw new new ExceptionException(("{"{$$filenamefilename}} : no such file" : no such file") ;) ;

}}161619:25:1919:25:19 Programmation Web 2011-2012Programmation Web 2011-2012

Page 17: PHP Création et manipulation d'images

Encapsulation objet : constantesEncapsulation objet : constantes

        /**/**

          * @var array* @var array

          */*/

        privateprivate  staticstatic  $$_factory_types_factory_types  ==  arrayarray((

                        selfself::::GD,GD,

                        selfself::::GD2PART,GD2PART,

                        selfself::::GD2,GD2,

                        selfself::::GIF,GIF,

                        selfself::::JPEG,JPEG,

                        selfself::::PNG,PNG,

                        selfself::::WBMP,WBMP,

                        selfself::::XBM,XBM,

                        selfself::::XPM,XPM,

                        )) ; ;171719:25:1919:25:19 Programmation Web 2011-2012Programmation Web 2011-2012

Page 18: PHP Création et manipulation d'images

Encapsulation objet : usineEncapsulation objet : usine

class GDImage class GDImage {{

        constconst GD       GD      == ' 'gdgd' ;' ;

        constconst GD2PART  GD2PART == ' 'gd2partgd2part' ;' ;

        constconst GD2      GD2     == ' 'gd2gd2' ;' ;

        constconst GIF      GIF     == ' 'gifgif' ;' ;

        constconst JPEG     JPEG    == ' 'jpegjpeg' ;' ;

        constconst PNG      PNG     == ' 'pngpng' ;' ;

        constconst WBMP     WBMP    == ' 'wbmpwbmp' ;' ;

        constconst XBM      XBM     == ' 'xbmxbm' ;' ;

        constconst XPM      XPM     == ' 'xpmxpm' ;' ;

  

181819:25:1919:25:19 Programmation Web 2011-2012Programmation Web 2011-2012

Page 19: PHP Création et manipulation d'images

191919:25:2019:25:20 Programmation Web 2011-2012Programmation Web 2011-2012

Création d'images : vision objetCréation d'images : vision objet

<<imgimg  srcsrc=="img.php""img.php"

altalt=="Mon image""Mon image"

heightheight=="152""152"  widthwidth=="210""210">><?php<?php

require_oncerequire_once((''gdimage.class.phpgdimage.class.php'')) ; ;

// Création// Création

$$imim

  == GDImage GDImage::::createFromSizecreateFromSize((100100, , 100100)) ; ;

// Manipulations// Manipulations

$$redred  ==  $$imim->->colorAllocatecolorAllocate((255255, , 00, , 00)) ; ;

$$imim->->filledRectanglefilledRectangle((00, , 00,,

9999, , 9999, , $$redred)) ; ;

// Envoi vers le navigateur// Envoi vers le navigateur

headerheader((''Content-type: image/pngContent-type: image/png'')) ; ;

$$imim->->PNGPNG()() ; ;

// Libération mémoire// Libération mémoire

// Automatique, à la destruction de $im// Automatique, à la destruction de $im

Peut dépendre de paramètres Peut dépendre de paramètres GET :GET :

•img.php?t=Coucouimg.php?t=Coucou•img.php?r=10&v=120&b=255img.php?r=10&v=120&b=255•img.php?i=im.jpgimg.php?i=im.jpg•……

Page 20: PHP Création et manipulation d'images

Comparaison non objet / objetComparaison non objet / objet

202019:25:2019:25:20 Programmation Web 2011-2012Programmation Web 2011-2012

<?php<?php// Création// Création$$imim == imageCreateimageCreate((100100, , 100100)) ;;

// Manipulations// Manipulations$$redred = = imageColorAllocateimageColorAllocate(($$imim,, 255255, , 00, , 00)) ;;imageFilledRectangleimageFilledRectangle(($$imim, , 00, , 00,, 9999, , 9999, , $$redred)) ;;

// Envoi vers le navigateur// Envoi vers le navigateurheaderheader((''Content-Type: image/pngContent-Type: image/png'')) ;;imagePNGimagePNG(($$imim)) ;;

// Libération mémoire// Libération mémoireimageDestroyimageDestroy(($$imim)) ;;

<?php<?php

require_oncerequire_once((''gdimage.class.phpgdimage.class.php'')) ; ;

// Création// Création

$$imim

  == GDImage GDImage::::createFromSizecreateFromSize((100100, , 100100)) ; ;

// Manipulations// Manipulations

$$redred  ==  $$imim->->colorAllocatecolorAllocate((255255, , 00, , 00)) ; ;

$$imim->->filledRectanglefilledRectangle((00, , 00,,

9999, , 9999, , $$redred)) ; ;

// Envoi vers le navigateur// Envoi vers le navigateur

headerheader((''Content-type: image/pngContent-type: image/png'')) ; ;

$$imim->->PNGPNG()() ; ;

// Libération mémoire// Libération mémoire

// Automatique, à la destruction de $im// Automatique, à la destruction de $im