Wednesday, October 21, 2009

Getting Started








Getting Started


To get started, we're going to create a simple imagejust an image showing a background colorand then send it as a JPEG image to the browser. To start, you create an image object with imagecreate, which you use like this:



imagecreate(int x_size, int y_size)


The x_size and y_size values are in pixels. Here's how we create our first image:



$image_height = 100;
$image_width = 300;

$image = imagecreate($image_width, $image_height);
.
.
.


To set colors for the image, you use imagecolorallocate, passing it the image you're working with, as well as the red, green, and blue components as values from 0 to 255:



imagecolorallocate(resource image, int red, int green, int blue)


The first time you call imagecolorallocate, this function sets the background color. Subsequent calls set various drawing colors, as we'll see. Here's how we set the background color to light gray (red = 200, green = 200, blue = 200):



$image = imagecreate($image_width, $image_height);

$back_color = imagecolorallocate($image, 200, 200, 200);
.
.
.


To send a JPEG image back to the browser, you have to tell the browser that you're doing so with the header function to set the image's type, and then you send the image with the imagejpeg function like this (do this before any other output is sent to the browser):



$image_height = 100;
$image_width = 300;

$image = imagecreate($image_width, $image_height);

$back_color = imagecolorallocate($image, 200, 200, 200);

header('Content-Type: image/jpeg');
imagejpeg($image);
.
.
.


Here are some of the image-creating functions for various image formats:



  • imagegif.
    Output a GIF image to browser or file


  • imagejpeg.
    Output a JPEG image to browser or file


  • imagewbmp.
    Output a WBMP image to browser or file


  • imagepng.
    Output a PNG image to browser or file


After sending the image, you can destroy the image object with the imagedestroy function; all this is shown in phpbox.php, Example 1.


Example 1. Displaying an image, phpbox.php



<?php
$image_height = 100;
$image_width = 300;

$image = imagecreate($image_width, $image_height);

$back_color = imagecolorallocate($image, 200, 200, 200);

header('Content-Type: image/jpeg');
imagejpeg($image);

imagedestroy($image);
?>



The results appear in Figure 1, where you can see our image, which is simply all background color. Cool, a JPEG image created on the server!


Figure 1. Displaying an image.

[View full size image]









    No comments: