PHP Dynamic Image Tutorial

PHP Dynamic Image Tutorial thumbnail
You can create images on the fly using PHP.

PHP enables you to create dynamic webpages that include generated images using GD library processes. The open-source code library contains several image-building functions, including those for setting colors, fonts and size. The GD library is bundled with PHP, but you can configure it or install a different version using the instructions available at the PHP.net site.

Instructions

    • 1

      Open your PHP file using a PHP, text or HTML editor.

    • 2

      Type the following code to create your own Captcha or security string image. Take note of the explanatory comments, preceded by slashes (//). Change the function parameter values to modify the image output according to your needs:

      <?php

      function create_image()
      {
      // header indicating the file type is necessary to display the image data
      header("Content-Type: image/jpeg");

      // generate five-character random string for the Captcha
      // $cap variable holds the string to check user input against
      $randnum = md5(rand(0,999));
      $cap = substr($randnum, 20, 5);

      // set image width and height variables
      $w = 80;
      $h = 32;

      // create image resource using width and height
      $image = ImageCreate($w, $h);

      // set colors using rgb numbers
      $white = ImageColorAllocate($image, 255, 255, 255);
      $red = ImageColorAllocate($image, 255, 50, 0);

      // color the box with params: image resource, x, y, color
      ImageFill($image, 0, 0, $red);

      // add white string to box with params: image, font (1-5), x, y, string and color
      ImageString($image, 5, 20, 8, $cap, $white);

      // output generated jpg image
      ImageJpeg($image);

      // clear resources
      ImageDestroy($image);
      }

      // call the function to display the generated image
      create_image();
      exit();

      ?>

    • 3

      Save the file and transfer it to your Web server. Type the file URL in a Web browser to test it.

Related Searches:

References

Resources

  • Photo Credit Jupiterimages/Comstock/Getty Images

Comments

Related Ads

Featured