PHP Developers Cookbook (2nd Edition)

18.2 Opening a Preexisting Image

You want to open a preexisting image for manipulation rather than creating an image from scratch.

Technique

Use the ImageCreateFrom* functions instead of the combination of the ImageCreate and Image* functions:

<?php // Opening a pre-existing PNG $im_ping = ImageCreateFromPng("someimage.png"); // Opening a pre-existing GIF $im_gif = ImageCreateFromGif("someimage.gif"); // Opening a pre-existing JPEG $im_jpeg = ImageCreateFromJpeg("someimage.jpg"); ?>

Comments

The ImageCreateFrom* functions enable you to open preexisting images as GD streams so that you can then manipulate them. Note that to use the ImageCreateFromGif() function, you must have GD 1.6 or earlier; to access the ImageCreateFromJpeg() function, you must have GD 1.8 or greater; for PNG support, you need GD 1.3 or greater.

After you have a GD stream to the image, manipulations of the image are done the same way as if you had created an image by using the ImageCreate() function. Consider the following script, which adds text to the middle of this image:

<?php header("Content-type: image/png"); if (($im = ImageCreateFromPng("generic.png")) == "") { echo "Error, could not open generic.png for manipulation!"; exit; } $red = ImageColorAllocate($im, 255, 0, 0); ImageString($im, 3, 20, 10, "Home", $red); ImagePng($im); // Print the Image out to the browser ?>

Категории