Chapter 2.6-Graphics
Chapter 2.6-Graphics
Creating Images:
An image is a rectangle of pixels of various colors. Colors are identified by their position in the palette, an
array of colors. Each entry in the palette has three separate color values: one for red, one for green, and one
for blue. Each value ranges from 0 to 255. With 256 possible values for each of red, green, and blue, there
are 16,777,216 possible colors for each pixel. Some file formats limit the number of colors that can be used
e.g., GIF supports no more than 256 colors.
Image files are available various file formats like GIF, JPEG, PNG, etc. Different file formats handle image
transparency, which controls whether and how the background shows through the image, in different ways.
PNG, support an alpha channel, an extra value for every pixel reflecting the transparency at that point. GIF,
simply designate one entry in the palette as indicating transparency. JPEG, don’t support transparency at all.
Anti-aliasing is where pixels at the edge of a shape are moved or re-colored to make a gradual ttransition
between the shape and its background. This prevents the rough and uneven edges that can make for
unappealing images.
imagecreatetruecolor() function : It is an inbuilt function in PHP which is used to create a new true color
image. This function returns a blank image of given size.
Syntax :
imagecreatetruecolor(width,height)
width: This parameter is used to set the width of image.
height: This parameter is used to set the height of image.
Note: In general imagecreatetruecolor() function is used instead of imagecreate() function
because imagecreatetruecolor() function creates high quality images.
imagecolorallocate() function : It is an inbuilt function in PHP which is used to set the color in an image.
This function returns a color which is given in RGB format.
Syntax:
$color = imagecolorallocate(image, red, green, blue);
image: It indicates image for allocation of colors.
red: This parameter is used to set value of red color component.
green: This parameter is used to set value of green color component.
blue: This parameter is used to set value of blue color component.
imagefilledrectangle() function : It is an inbuilt function in PHP which is used to create a filled rectangle.
This function creates a rectangle filled with given color in the image. In this function, parameters are used to
specify the dimensions of the rectangle by passing the coordinates of the top-left and bottom-right corners:
Syntax :
imagefilledrectangle(image, tlx, tly, brx, bry, color);
image: It is used to indicate image with specific size .
x1: This parameter is used to set the x-coordinate for point (top left).
y1: This parameter is used to set the y-coordinate for point (top left).
x2: This parameter is used to set the x-coordinate for point (bottom right).
y2: This parameter is used to set the y-coordinate for point (bottom right).
color: This parameter specify color to be filled in the image.
Content-Type header: It is to specify type of image being created to the browser. Once that is done, we call
the appropriate output function.
Set the HTTP header immediately before calling the output generating function.. If Content-Type is set at
the start of the script, any errors that are generated are treated as image data and the browser displays a
broken image icon.
Syntax :
imagegif(image [, filename ]);
imagejpeg(image [, filename [, quality ]]);
imagepng(image [, filename ]);
imagewbmp(image [, filename ]);
If no filename is given, the image is output to the browser; otherwise, it creates or overwrites) the image to
the given file path. The quality argument for JPEGs is a number from 0 (worst-looking) to 100 (best-
looking). The lower the quality, the smaller the JPEG file. The default setting is 75.
Example 1 : Output :
<?php
$image = imagecreate(200, 200);
$color = imagecolorallocate($image, 255, 225, 200);
imagefilledrectangle($image, 150, 150, 350, 350, $color);
header("Content-Type: image/jpeg");
imagejpeg($image);
?>
Example 2:
<?php Output :
$image = imagecreate(200, 200);
$white = imagecolorallocate($image, 0xFF, 0xFF, 0xFF);
$black = imagecolorallocate($image, 0x00, 0x00, 0x00);
imagefilledrectangle($image, 50, 50, 150, 150, $black);
header("Content-Type: image/jpeg");
imagejpeg($image);
?>
Changing the Output Format: generating an image stream of a different type requires only two changes to
the script: send a different Content-Type and use a different image generating function.
Example:
Changing jpeg file format to png file format:
<?php
$image = imagecreate(200, 200);
$white = imagecolorallocate($image, 0xFF, 0xFF, 0xFF);
$black = imagecolorallocate($image, 0x00, 0x00, 0x00);
imagefilledrectangle($image, 50, 50, 150, 150, $black);
header("Content-Type: image/png");
imagepng($image);
?>
Example: Generates PNG files if PNG is supported, JPEG files if PNG is not supported, and GIF files if
neither PNG nor JPEG is supported.
<?php
$image = imagecreate(200, 200);
$white = imagecolorallocate($image, 0xFF, 0xFF, 0xFF);
$black = imagecolorallocate($image, 0x00, 0x00, 0x00);
imagefilledrectangle($image, 50, 50, 150, 150, $black);
if (imagetypes() & IMG_PNG) {
header("Content-Type: image/png");
imagepng($image)
}
else if (imagetypes() & IMG_JPG) {
header("Content-Type: image/jpeg");
imagejpeg($image);
}
else if (imagetypes() & IMG_GIF) {
header("Content-Type: image/gif");
imagegif($image);
}
imagesetpixel() function : It is an inbuilt function in PHP which is used to draw a pixel at the specified
coordinate.
Syntax:
imagesetpixel(image,x, y, color )
image: It specifies the resource image.
x: It specifies the x-coordinate of pixel.
y: It specifies the y-coordinate of pixel.
color: It specifies the color of pixel.
Example :
$red = imagecolorallocate($image, 255, 0, 0);
imagesetpixel($image, 10, 50, $red);
Program : To plot three pixels Output :
<?php
$image = imagecreate(200, 200);
$black = imagecolorallocate($image, 0x00, 0x00, 0x00);
$yellow=imagecolorallocate($image,225,200,100);
imagesetpixel($image, 10, 50, $yellow);
imagesetpixel($image, 100, 100, $yellow);
imagesetpixel($image, 10, 150, $yellow);
header("Content-Type: image/png");
imagepng($image);
?>
imageline() function : It is an inbuilt function in PHP which is used to draw a line between the two given
points.
Syntax:
imageline(image, start_x, start_ y, end_x, end_ y, color);
image: It specifies the image resource to work on.
x1: It specifies the starting x-coordinate.
y1: It specifies the starting y-coordinate.
x2: It specifies the ending x-coordinate.
y2: It specifies the ending y-coordinate.
color: It specifies the line color.
Example:
$yellow=imagecolorallocate($image,225,200,100);
imageline($image,10,10,200,200,$yellow);
Program : To plot a line Output :
<?php
$image = imagecreate(200, 200);
$black = imagecolorallocate($image, 0x00, 0x00, 0x00);
$yellow=imagecolorallocate($image,225,200,100);
imageline($image,10,10,150,150,$yellow);
header("Content-Type: image/png");
imagepng($image);
?>
imagefilledrectangle() function : It is an inbuilt function in PHP which is used to create a filled rectangle.
This function creates a rectangle filled with a given color in the image.
Syntax :
imagefilledrectangle(image, tlx, tly, brx, bry, color);
image: It specifies the image resource to work on..
x1: This parameter is used to set the upper left x-coordinate.
y1: This parameter is used to set the upper left y-coordinate.
x2: This parameter is used to set the bottom right x-coordinate.
y2: This parameter is used to set the bottom right y-coordinate.
color: It specifies the line color.
Example :
$purple=imagecolorallocate($image,150,100,200);
imagefilledrectangle($image,50,100,150,200,$purple);
Imagefilledpolygon() function : It is an inbuilt function in PHP which is used to draw a filled polygon.
Syntax :
imagefilledpolygon(image, points, number, color);
image: It specifies the image resource to work on.
points: This parameter is used to hold the consecutive vertices of polygon.
num_points: This parameter contains total number of vertices in a polgon. It must be greater
then 3, because minimum three vertices required to create a polygon.
color: It specifies the line color.
Example :
$purple=imagecolorallocate($image,150,100,200);
imagefilledpolygon($image,$values,5,$purple);
Program : To plot filled polygon Output :
<?php
$image = imagecreate(300, 300);
$black = imagecolorallocate($image, 0x00, 0x00,
0x00);
$yellow=imagecolorallocate($image,225,200,100);
$values = array(
150, 50, // Point 1 (x, y)
55, 119, // Point 2 (x, y)
91, 231, // Point 3 (x, y)
209, 231, // Point 4 (x, y)
245, 119 // Point 5 (x, y)
);
imagefilledpolygon($image,$values,5,$yellow);
header("Content-Type: image/png");
imagepng($image);
?>
imagearc() function : It is an inbuilt function in PHP which is used to create an arc of a circle centered at
the given coordinates.
Syntax :
imagearc(image, center_x, center_ y, width, height, start, end, color);
image: It specifies the image resource to work on.
cx: It is used to set x-coordinate of the center.
cy: It is used to set y-coordinate of the center.
width: The width of arc.
height: The height of arc.
start: It is used to set the arc start angle, in degrees.
end: It is used to set the arc end angle, in degrees. 0° is located at the three-o’clock
position, and the arc is drawn clockwise.
color: It sets the color of image.
To form a circle specify start as 0 and end as 360.
Example :
$yellow=imagecolorallocate($image,225,200,100);
imagearc($image, 200, 150, 150, 250, 0, 360, $yellow);
imagefill() function : It is an inbuilt function in PHP which is used to fill the image with the given color.
This function performs a flood fill, changing the color of the pixels starting at the given location.
Syntax :
imagefill(image, x, y, color);
image: It specifies the image resource to work on.
x: This parameter is used to set x-coordinate of starting point.
y: This parameter is used to set y-coordinate of starting point.
color: It sets the color of image.
Example :
$yellow=imagecolorallocate($image,225,200,100);
imagefill($image,10,50,$yellow);
imagefilltoborder() function : It is an inbuilt function in PHP which is used to performs a flood fill with a
specific color and add a border with a border color.
Syntax :
imagefilltoborder(image, x, y, bordercolor, color);
image: It specifies the image to be worked upon.
x: It specifies the x-coordinate of start.
y: It specifies the y-coordinate of start.
border: It specifies the border color.
color: It specifies the fill color.
Example :
$purple=imagecolorallocate($image,150,100,200);
imagefilltoborder($image,0,0, $yellow,$purple);
imagerotate() function : It is an inbuilt function in PHP which is used to rotate an image with a given
angle in degrees.
Syntax :
imagerotate(image, angle, background_color);
$image: It specifies the image to be worked upon.
$angle: This parameter holds the rotation angle in degrees. The rotation angle is used to
rotate an image in anticlockwise direction.
$background_color: This parameter holds the background color of uncovered zone after
rotation.
Example :
$purple=imagecolorallocate($image,150,100,200);
$image=imagerotate($image, 120,$purple);
<?php
$image = imagecreate(200, 200);
$white = imagecolorallocate($image, 0xFF, 0xFF, 0xFF);
$black = imagecolorallocate($image, 0x00, 0x00, 0x00);
imagefilledrectangle($image, 50, 50, 150, 150, $black);
imagestring($image, 5, 50, 160, "A Black Box", $black);
header("Content-Type: image/png");
imagepng($image);
?>
Scaling Images :
There are two ways to change the size of an image : imagecopyresized() & imagecopyresampled()
imagecopyresized() function : It is an inbuilt function in PHP which is used to copy a rectangular portion
of one image to another image. dst_image is the destination image, src_image is the source image
identifier.
Syntax :
imagecopyresized(dst_image, src_image, dst_x, dst_y,src_x, src_y, dst_w, dst_h, src_w, src_h)
dst_image: It specifies the destination image resource.
src_image: It specifies the source image resource.
dst_x: It specifies the x-coordinate of destination point.
dst_y: It specifies the y-coordinate of destination point.
src_x: It specifies the x-coordinate of source point.
src_y: It specifies the y-coordinate of source point.
dst_w: It specifies the destination width.
dst_h: It specifies the destination height.
src_w: It specifies the source width.
src_h: It specifies the source height.
Example :
Code to display original image : Output :
<?php
list($s_width,$s_height)=getimagesize('s1.jpg'); THis line is used to get the
$s_image=imagecreatefromjpeg('s1.jpg'); width and height from the
source mage file
header('Content-Type:image/jpeg');
imagejpeg($s_image);
?>
Code to display re-sized image : Output :
<?php
list($s_width,$s_height)=getimagesize('s1.jpg');
$s_image=imagecreatefromjpeg('s1.jpg');
$d_image=imagecreate(150,150);
imagecopyresized($d_image,$s_image,0,0,50,50,200,200,$s_width,$s_he
ight);
header('Content-Type:image/jpeg');
imagejpeg($d_image);
?>
imagecopyresampled() function : It is used to copy a rectangular portion of one image to another image,
smoothly interpolating pixel values so that, in particular, reducing the size of an image still retains a great
deal of clarity.
Syntax :
imagecopyresampled(dst_image, src_image, dst_x, dst_y,src_x, src_y, dst_w, dst_h, src_w, src_h)
dst_image: It specifies the destination image resource.
src_image: It specifies the source image resource.
dst_x: It specifies the x-coordinate of destination point.
dst_y: It specifies the y-coordinate of destination point.
src_x: It specifies the x-coordinate of source point.
src_y: It specifies the y-coordinate of source point.
dst_w: It specifies the destination width.
dst_h: It specifies the destination height.
src_w: It specifies the source width.
src_h: It specifies the source height.
Example :
<?php
list($s_width,$s_height)=getimagesize('s1.jpg');
$s_image=imagecreatefromjpeg('s1.jpg');
$d_image=imagecreate(150,150);
imagecopyresampled($d_image,$s_image,0,0,50,50,200,200,$s_width,$s_height);
header('Content-Type:image/jpeg');
imagejpeg($d_image);
?>
Output : Same as above.
Note : The imagecopyresampled() function is slower, but features pixel interpolation to give smooth edges
and clarity to the resized image.
require() function : The FPDF library is a set of PHP code that can be included in scripts with the require()
function. This statement takes all the text/code/markup that exists in the specified file and copies it into the
file that uses the include statement.
Syntax :
require("path for fpdf.php file");
Example :
require("fpdf/fpdf.php");
Creating instance : A new instance of the FPDF class is created to call all methods used for creating pdf
file.
Example :
$pdf = new FPDF();
Methods can be access using the ->(tends to) operator.
setFont() function : It is used to set the font for the output(character string) to be displayed/printed in pdf
document. It is mandatory to call this method at least once before printing text or the resulting document
would not be valid.The font can be either a standard one or a font added via the AddFont() method.
Syntax :
SetFont(string family [, string style [, float size]])
- family specify font name. It can be either a name defined by AddFont() or one of the standard
families : Courier (fixed-width) / Helvetica or Arial (synonymous ; sans serif) / Times (serif) /
Symbol (symbolic) / ZapfDingbats (symbolic)
- style specify font style.Possible values are :empty string: regular/B: bold/I: italic/U: underline or
any combination. The default value is regular.
- size specify font size in points. The default value is the current size. If no size has been specified
since the beginning of the document, the value taken is 12.
Example :
$pdf->setFont("Arial", 'B', 16);
cell() method : Then, using the cell method call, you can place the output on your created document.
The cell concept in the FPDF library is that of a rectangular area on the page that you can create and control.
Syntax :
cell(float w [, float h [, string txt [, mixed border [, int ln [, string align [, int fill [, mixed link]]]]]]])
- w specify cell width. If 0, the cell extends up to the right margin.
- h specify Cell height. Default value: 0.
- txt specify string to print. Default value: empty string.
- border indicates if borders must be drawn around the cell. The value can be either a number as 0
(no border) / 1 (frame) or a string containing some or all of the following characters (in any order) :
L(left), T(top),R (right),B(bottom). Default value: 0.
- ln Indicates where the current position should go after the call. Possible values are: 0(to the right),
1(to the beginning of the next line), 2(below). Default value: 0.
- align allows to be at center or align the text. Possible values are: L or empty string: left align
(default value) ,C(center) ,R( right align)
- fill indicates if the cell background must be painted (true) or transparent (false). Default value: false.
- link URL or identifier returned by AddLink().
Example :
$pdf->cell(40, 10, "Hello Out There!");
output() function : It is used to send all contents to the browser to display on screen(pdf file).
Example :
$pdf->output();
$pdf->ln(4.5);
The above statement tell the PDF class to move down 4 ½ inches on the page with the ln(4.5) statement, and
continue the output generation from that point.
You can include any other font family for which you have the definition file. Use the AddFont() method for
this operation.
SetTextColor() method : This method takes the existing font definition and simply changes the color of the
text. Be sure to call this method before you use the cell() method so that the content of the cell can be
changed. The color parameters are combinations of red, green, and blue numeric constants from 0 (none) to
255 (full color). If you do not pass in the second and third parameters, then the first number will be a shade
of gray with red, green, and blue values equal to the single passed value.
Defines the color used for text. It can be expressed in RGB components or gray scale. The method can be
called before the first page is created and the value is retained from page to page.
Syntax :
SetTextColor(int r [, int g, int b]);
- r specify value for red component (between 0 and 255).if not, indicates the gray level.
- g specify value for green component (between 0 and 255)
- b specify value for blue component (between 0 and 255)
Example : SetTextColor(100,150,200);
AliasNbPages() method : It is used to track the overall page count in the PDF document before it is sent to
the browser.
Example :
<?php
require("fpdf/fpdf.php");
class MyPDF extends FPDF
{
function header()
{
global $title;
$this->setFont("Times", '', 12);
$this->setDrawColor(0, 0, 180);
$this->setFillColor(230, 0, 230);
$this->setTextColor(0, 0, 255);
$this->setLineWidth(1);
$width = $this->getStringWidth($title) + 150;
$this->cell($width, 9, $title, 1, 1, 'C', 1);
$this->ln(10);
}
function footer()
{
//Position at 1.5 cm from bottom
$this->setY(-15);
$this->setFont("Arial", 'I', 8);
$this->cell(0, 10,
"This is the page footer -> Page {$this->pageNo()}/{nb}", 0, 0, 'C');
}}
$title = "FPDF Library Page Header";
$pdf = new MyPDF('P', 'mm', 'Letter');
$pdf->aliasNbPages();
$pdf->addPage();
$pdf->setFont("Times", '', 24);
$pdf->cell(0, 0, "some text at the top of the page", 0, 0, 'L');
$pdf->ln(225);
$pdf->cell(0, 0, "More text toward the bottom", 0, 0, 'C');
$pdf->addPage();
$pdf->setFont("Arial", 'B', 15);
$pdf->cell(0, 0, "Top of page 2 after header", 0, 1, 'C');
$pdf->output();
?>
Images :
The FPDF library can also handle image insertion within the PDF document.
image() method : It is used to add an image into a pdf file.
Syntax :
Image(“image filename”, x,y,width,height)
- filename specify path for the image to use
- x coordinate
- y coordinate
- width of the image
- height of the image
Example :
image("php-tiny.jpg", 10, 10.5, 15, 8.5);