Hot File

Dynamic Image Generation in PHP

View: 343    Dowload: 0   Comment: 0   Post by: hanhga  
Author: none   Category: Forum PHPBB, VBB   Fields: Other

0 point/1 review File has been tested

At first, have a look at the following script that creates captcha image. Next, we will consider each step of image generation in details.

Introduction

Creating security images on the fly :

At first, have a look at the following script that creates captcha image. Next, we will consider each step of image generation in details.

<?php 
//Send a generated image to the browser 
create_image(); 
exit(); 

function create_image() 
{ 
    //Let's generate a totally random string using md5 
    $md5 = md5(rand(0,999)); 
    //We don't need a 32 character long string so we trim it down to 5 
    $pass = substr($md5, 10, 5); 

    //Set the image width and height 
    $width = 100; 
    $height = 20;  

    //Create the image resource 
    $image = ImageCreate($width, $height);  

    //We are making three colors, white, black and gray 
    $white = ImageColorAllocate($image, 255, 255, 255); 
    $black = ImageColorAllocate($image, 0, 0, 0); 
    $grey = ImageColorAllocate($image, 204, 204, 204); 

    //Make the background black 
    ImageFill($image, 0, 0, $black); 

    //Add randomly generated string in white to the image
    ImageString($image, 3, 30, 3, $pass, $white); 

    //Throw in some lines to make it a little bit harder for any bots to break 
    ImageRectangle($image,0,0,$width-1,$height-1,$grey); 
    imageline($image, 0, $height/2, $width, $height/2, $grey); 
    imageline($image, $width/2, 0, $width/2, $height, $grey); 
 
    //Tell the browser what kind of file is come in 
    header("Content-Type: image/jpeg"); 

    //Output the newly created image in jpeg format 
    ImageJpeg($image); 
    
    //Free up resources
    ImageDestroy($image); 
} 
?>

To create a new image or edit an existing one, we need to create image identifier. In the preceding example we created an empty canvas by calling ImageCreate() function, passing it width and height  of a new image as a parameters. Another way to do it is to read the existing image from the file.  Depending on the file format you can do it using one of the following functions: ImageCreateFromPNG(), ImageCreateFromGIF(), ImageCreateFromJPEG(). Parameter of each function is a file name.

Then, we need to choose colors to be used while painting. For this we can use ImageColorAllocate() function and image identifiers for red, green, and blue (RGB) components of necessary color will be passed as parameters.

On the next step, we will generate our image. First, using ImageFill() function we will create black background.  Parameters of this function are: image identifier, initial coordinates of the area to be filled and fill color.  Then, we will use ImageString() function to add text to the image. Its parameters are – image identifier, font, coordinates for the first text position and text color. Finally, we will draw two lines and a rectangular to protect our image a little bit.  Please note, that the final point of the rectangular has the following coordinates: $width-1 and $height-1. If they were equal to $width and $height, than the rectangular would have exceeded canvas frame.

When we had created the image, we can output it either to a browser, or to a file. Our example shows how to output it to the browser. We need to inform the browser, that we will output the image, not the text or html-code. To do it, call Header() function, setting image MIME-type. It’s worth mentioning that Header() function can not be executed if HTTP header has already been sent.   After sending the header we can output our image using ImageJpeg() function, passing it image identifier as a parameter.

When we have finished working with the image we need to free up resources using ImageDestroy() function.

Building a bar chart :

In the example below, using graphic functions we will build a bar chart based on the values stored in MySQL database. In our case, values represent poll results.

In this example we will use poll database. To create it run the following SQL script in your MySQL server:

CREATE DATABASE `poll`;
USE poll;

CREATE TABLE `results` ( 
   book_type VARCHAR(50), 
   num_votes INT
);

INSERT INTO `results` values  
    ('Classic', 15), 
    ('Fantasy', 7), 
    ('Humor', 32), 
    ('Mystery', 12), 
    ('Poetry', 25);

Script building a bar chart is quite long, so let's divide it into two parts and discuss them separately. The first part of the script connects to MySQL database and requests data that will be represented in the bar chart.

<?php
//Querying the database to get poll results

//connection to the database 
$dbhandle = mysql_connect("localhost", "root", "") 
  or die("Unable to connect to MySQL"); 

//select a database to work with 
$selected = mysql_select_db("poll",$dbhandle) 
  or die("Could not select examples"); 

//execute the SQL query and return records 
$result = mysql_query("SELECT * FROM results"); 

$num_poller = mysql_num_rows($result); 
$total_votes = 0; 

//fetch the data from the database 
while ($row = mysql_fetch_array($result)) { 
  $total_votes += $row{'num_votes'};  //calculating total number of votes
} 

//nulling the pointer $result
mysql_data_seek($result,0); 

//close the connection 
mysql_close($dbhandle);

In the second part of the script first of all we will calculate variables needed to build the chart. Then, we prepare primary image and actually output data. Results for each genre are picked from the database one by one, percentage of votes is calculated, and then bars and explanatory notes are outputted.

In this script we are using TrueType fonts to get anti-aliased text. Functions that work with the TrueType fonts have its own peculiarities. First, you need to point where the fonts are located. For this, system variable GDFONTPATH is set. Then, we need to set the font name. TrueType fonts are rendered using  ImageTTFText().

We have already discussed above all functions used for drawing, the code has been commented and is quite clear, so you shouldn’t have any trouble.

//Tell gd2, where your fonts reside 
putenv('GDFONTPATH=C:\WINDOWS\Fonts'); 
$font = 'arial'; 

//Set starting point for drawing 
$y = 50; 

//Specify constant values 
$width = 700; //Image width in pixels
$bar_height = 20; //Bars height
$height = $num_poller * $bar_height * 1.5 + 70; //Calculating image height 
$bar_unit = ($width - 400) / 100; //Distance on the bar chart standing for 1 unit

//Create the image resource 
$image = ImageCreate($width, $height); 

//We are making four colors, white, black, blue and red 
$white = ImageColorAllocate($image, 255, 255, 255); 
$black = ImageColorAllocate($image, 0, 0, 0); 
$red   = ImageColorAllocate($image, 255, 0, 0); 
$blue  = imagecolorallocate($image,0,0,255); 

//Create image background 
ImageFill($image,$width,$height,$white); 
//Draw background shape 
ImageRectangle($image, 0, 0, $width-1, $height-1, $black); 
//Output header 
ImageTTFText($image, 16, 0, $width/3 + 50, $y - 20, $black, $font, 'Poll Results'); 

while ($row = mysql_fetch_object($result)) { 
  if ($total_votes > 0) 
    $percent = intval(round(($row->num_votes/$total_votes)*100)); 
  else 
    $percent = 0; 

//Output header for a particular value 
ImageTTFText($image,12,0,10, $y+($bar_height/2), $black, $font, $row->book_type); 
//Output percentage for a particular value 
ImageTTFText($image, 12, 0, 170, $y + ($bar_height/2),$red,$font,$percent.'%'); 

$bar_length = $percent * $bar_unit; 

//Draw a shape that corresponds to 100% 
ImageRectangle($image, $bar_length+221, $y-2, (220+(100*$bar_unit)), $y+$bar_height, $black); 
//Output a bar for a particular value 
ImageFilledRectangle($image,220,$y-2,220+$bar_length, $y+$bar_height, $blue); 
//Output the number of votes 
ImageTTFText($image, 12, 0, 250+100*$bar_unit, $y+($bar_height/2), $black, $font, $row->num_votes.' votes cast.'); 

//Going down to the next bar 
$y = $y + ($bar_height * 1.5); 

} 

//Tell the browser what kind of file is come in 
header("Content-Type: image/jpeg"); 

//Output the newly created image in jpeg format 
ImageJpeg($image); 

//Free up resources 
ImageDestroy($image); 
?>

Using dynamically generated images on the other pages :

Since the header can be sent only once and it is the only way to tell the browser that you are going to send image, it is not so easy to insert automatically generated images to the regular pages. There are three ways to do it:

  • The whole page can consist of the image.
  • You can save image in the file and then refer to it using <img> HTML descriptor.
  • You can  put a script producing image in HTML descriptor, e.g.:
<img height="120" alt="Dynamically generated image" src="generate_image.php" width="200">

 

 

Dynamic Image Generation in PHP

Dynamic Image Generation in PHP Posted on 17-12-2015  At first, have a look at the following script that creates captcha image. Next, we will consider each step of image generation in details. 5/10 343

Comment:

To comment you must be logged in members.

Files with category

  • Input Validation Using Filter Functions with php

    View: 374    Download: 0   Comment: 0   Author: none  

    Input Validation Using Filter Functions with php

    Category: Forum PHPBB, VBB
    Fields: Other

    2.25/2 review
    Filter functions in PHP might not be sexy, but they can improve the stability, security, and even maintainability of your code if you learn how to use them correctly.

  • The Open/Closed Principle in PHP

    View: 255    Download: 0   Comment: 0   Author: none  

    The Open/Closed Principle in PHP

    Category: Forum PHPBB, VBB
    Fields: Other

    0/2 review
    As usual, a good way to grasp what’s actually behind the curtain of the principle and how to take advantage of its benefits is by example. In this article I’ll be setting up a few approachable ones in an attempt to unveil the principle’s driving...

  • Dependency Injection with Pimple in PHP

    View: 291    Download: 0   Comment: 0   Author: none  

    Dependency Injection with Pimple in PHP

    Category: Forum PHPBB, VBB
    Fields: Other

    1.6666666666667/3 review
    In application development, we try to create independent modules so that we can reuse code in future projects. But, it’s difficult to create completely independent modules which provide useful functionality; their dependencies can cause maintenance...

  • Working with Directories in PHP

    View: 417    Download: 0   Comment: 0   Author: none  

    Working with Directories in PHP

    Category: Forum PHPBB, VBB
    Fields: Other

    2.25/2 review
    Let's start with simple listing the contents of a directory. We need three functions to perform this task: opendir(), readdir() and closedir(). The opendir() function takes one parameter, which is the directory we want to read, and returns a...

  • Guide to Email (Text / HTML / Attachments) in PHP

    View: 397    Download: 0   Comment: 0   Author: none  

    Guide to Email (Text / HTML / Attachments) in PHP

    Category: Forum PHPBB, VBB
    Fields: Other

    0/2 review
    At first let's consider how to send a simple text email messages. PHP includes the mail() function for sending email, which takes three basic and two optional parameters.

  • Dynamic Image Generation in PHP

    View: 343    Download: 0   Comment: 0   Author: none  

    Dynamic Image Generation in PHP

    Category: Forum PHPBB, VBB
    Fields: Other

    0/1 review
    At first, have a look at the following script that creates captcha image. Next, we will consider each step of image generation in details.

  • Form Processing with PHP

    View: 618    Download: 0   Comment: 0   Author: none  

    Form Processing with PHP

    Category: Forum PHPBB, VBB
    Fields: Other

    2.6666666666667/3 review
    Before you can process the information, you need to create an HTML form that will send information to your PHP script. There are two methods for sending data: POST and GET. These two types of sending information are defined in your HTML form...

  • Function in PHP

    View: 514    Download: 0   Comment: 0   Author: none  

    Function in PHP

    Category: Forum PHPBB, VBB
    Fields: Other

    2.5/2 review
    A function is a block of code which can be called from any point in a script after it has been declared. It is basically a compartmentalized PHP script designed to accomplish a single task. Furthermore, code contained within functions is ignored...

 
Newsletter Email

File suggestion for you

File top downloads

logo codetitle
Codetitle.com - library source code to share, download the file to the community
Copyright © 2015. All rights reserved. codetitle.com Develope by Vinagon .Ltd