WBP Topic 2 Notes
WBP Topic 2 Notes
Anonymous functions (Lambda) are PHP features which we do not use often
but they can be really useful in certain situations like passing a function as
an argument in another function, accessing a variable which is declared
outside the scope of the function etc.
function myRegularFunction(){
}
When you define a regular function you give it a name(myRegularFunction in this
cases). Now you can refer to this function using function name.For example, you
can call this function like this-
myRegularFunction();
Anonymous functions are similar to the regular function as they can contain
the same type of code, they accept arguments, return values and all…
function($argument1,$argument2){
};
If you have noticed there are two key difference between a regular function and an
anonymous function.
There is no function name(between function keyword and the opening
parenthesis() which tells PHP that we are creating an anonymous function.
There is a semicolon(;) after the function definition. This is because
anonymous functions definitions are expressions whereas regular function
definition is code constructs.
While the above code looks fine but it can not be called because this function
doesn’t have any name. This function cannot be referred anywhere but you can do
a lot of handy things with it-
You can assign it to a variable and can call it using the variable
name. Even you can store a bunch of different anonymous functions in a
single array.
You can pass this function to another function as a parameter. This is
known as Callback.
Return it from within an outer function so that it can access the outer
function’s variables. This is known as a closure.
$addition=function($arg1,$arg2){
echo $addition(20,50);
the output will be
sum = 70
Or even we can store multiple anonymous functions to an array like this-
$myarray = array(
echo $myarray[3]
Many PHP built-in functions accept callback or you can create your own
function which accepts callback function.
Let’s see some of the built-in function and understand their functionality
NOTE: array_map() works on a copy of array you pass to it. The Original array
remains untouched.
Here is example-
$num_array = array(1,2,3,4,5);
$new_array[]=$value*$value;
print_r($new_array);
this will output-
Array
(
[0] => 1 [1] => 4 [2] => 9 [3] => 16 [4] => 25
)
when we use a regular function a a callback function in array_map()
function square($num){
return $num*$num;
$new_array=array_map('square', $num_array);
print_r($new_array);
this will also output the same result.
$new_array = array_map(function($num){
return $num*$num;
}, $num_array);
print_r($new_array);
print_r($num_array);
this will output-
Array
(
[0] => 1
[1] => 4
[2] => 9
[3] => 16
[4] => 25
)
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
)
as you can see there is no change in $num_array array. its content remained same.
Confusing… right?
$user='Peter';
If you alter $user variable within closure it will not affect the original value. its
value will still be “Peter”. If you want to alter the original value you can use the
reference to $user as &$user in closure as below
}
Variable functions
PHP supports the concept of variable functions. This means that if a variable
name has parentheses appended to it, PHP will look for a function with the
same name as whatever the variable evaluates to, and will attempt to execute
it. Among other things, this can be used to implement callbacks, function
tables, and so forth.
<?php
function foo() {
function echoit($string)
{ echo $string;
$func = 'foo';
$func(); // This calls foo()
$func = 'bar';
$func = 'echoit';
?>
You can also call an object's method by using the variable functions feature.
<?php
class Foo{
function Variable() {
$name = 'Bar';
function Bar()
$funcname = "Variable";
?>
Basic Graphics Concepts
An image is a rectangle of pixels that have 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 (this color not present) to 255 (this color at full intensity).
Image files are rarely a straightforward dump of the pixels and the palette.
Instead, various file formats (GIF, JPEG, PNG, etc.) have been created that attempt to
compress the data somewhat to make smaller files.
Different file formats handle image transparency , which controls whether and
how the background shows through the image, in different ways. Some support an
alpha channel, an extra value for every pixel reflecting the transparency at that
point. Others simply designate one entry in the palette as indicating transparency.
Antialiasing is where pixels at the edge of a shape are moved or recolored to
make a gradual transition between the shape and its background. This prevents the
rough and jagged edges that can make for unappealing images. Some functions that
draw on an image implement antialiasing.
With 256 possible values for each of red, green, and blue, there are
16,777,216 possible colors for every pixel. Some file formats limit the number of
colors you can have in a palette (e.g., GIF supports no more than 256 colors); others
let you have as many colors as you need. The latter are known as true color formats,
because 24-bit color (8 bits for each of red, green, and blue) gives more hues than
the human eye can distinguish.
The arguments are the numeric RGB (red, green, blue) components of the
color. In Example 9-1, we wrote the color values in hexadecimal, to bring the
function call closer to the HTML color representation "#FFFFFF" and "#000000".
There are many drawing primitives in GD. Example 9-1 uses
ImageFilledRectangle( ), in which you specify the dimensions of the rectangle by
passing the coordinates of the top-left and bottom-right corners:
The next step is to send a Content-Type header to the browser with the
appropriate content type for the kind of image being created. Once that is done, we
call the appropriate output function. The ImageJPEG( ) , ImagePNG( ), and
ImageWBMP( ) functions create JPEG, PNG, and WBMP files from the image,
respectively:
If no filename is given, the image is sent to the browser. The quality argument
for JPEGs is a number from 0 (worst-looking) to 10 (best-looking). The lower the
quality, the smaller the JPEG file. The default setting is 7.5.
In Example 9-1, we set the HTTP header immediately before calling the
output-generating function ImagePNG( ). If, instead, you set the Content-Type at the
very start of the script, any errors that are generated are treated as image data and
the browser displays a broken image icon. Table 9-1 lists the image formats and their
Content-Type values.
Table 9-1. Content-Type values for image formats
ImageSetPixel(image, x, y, color);
There are two functions for drawing lines, ImageLine( ) and ImageDashedLine(
):
There are two functions for drawing rectangles, one that simply draws the
outline and one that fills the rectangle with the specified color:
Specify the location and size of the rectangle by passing the coordinates of the top-
left and bottom-right corners.
You can draw arbitrary polygons with the ImagePolygon( ) and
ImageFilledPolygon( ) functions:
Both functions take an array of points. This array has two integers (the x and y
coordinates) for each vertex on the polygon. The number argument is the number of
vertices in the array (typically count($points)/2).
The ellipse is defined by its center, width, and height (height and width are the same
for a circle). The start and end points of the arc are given as degrees counting
counterclockwise from 3 o'clock. Draw the full ellipse with a start of 0 and an end of
360.
There are two ways to fill in already-drawn shapes. The ImageFill( ) function
performs a flood fill, changing the color of the pixels starting at the given location.
Any change in pixel color marks the limits of the fill.
The ImageFillToBorder( ) function lets you pass the particular color of the limits of the
fill:
ImageFill(image, x, y, color);
ImageFillToBorder(image, x, y, border_color, color);
Images with Text
Often it is necessary to add text to images. GD has built-in fonts for this
purpose. Example 9-4 adds some text to our black square image.
Figure 9-2. The image with text The ImageString( ) function adds text to an
image. Specify the top-left point of the text, as well as the color and the font to use:
Scaling Images
There are two ways to change the size of an image. The ImageCopyResized( )
function is available in all versions of GD, but its resizing algorithm is crude and may
lead to jagged edges in your new images. The ImageCopyResampled( ) function is
new in GD 2.x and features pixel interpolation to give smooth edges and clarity to
resized images (it is, however, slower than ImageCopyResized( )). Both functions take
the same arguments:
ImageCopyResized(dest, src, dx, dy, sx, sy, dw, dh, sw, sh);
ImageCopyResampled(dest, src, dx, dy, sx, sy, dw, dh, sw, sh);
The dest and src parameters are image handles. The point (dx,dy) is the point
in the destination image where the region will be copied. The point (sx,sy) is the
upper-left corner of the source image. The sw, sh, dw, and dh parameters give the
width and height of the copy regions in the source and destination.
Dividing the height and the width by 4 instead of 2 produces the output shown in
Figure 9-10.
imagecopyresized
imagecopyresized — Copy and resize part of an image
Description
imagecopyresized ( resource $dst_image , resource $src_image , int $dst_x
, int $dst_y , int $src_x , int $src_y , int $dst_w , int $dst_h , int $
src_w , int $src_h ) : bool
If the source and destination coordinates and width and heights differ, appropriate
stretching or shrinking of the image fragment will be performed. The coordinates
refer to the upper left corner. This function can be used to copy regions within the
same image (if dst_image is the same as src_image) but if the regions overlap the
results will be unpredictable.
Parameters
dst_image-Destination image link resource.
dst_w-Destination width.
dst_h-Destination height.
src_w-Source width.
src_h-Source height.
Return Values
Examples
<?php
// File and new size
$filename = 'test.jpg';
$percent = 0.5;
// Content type
header('Content-Type: image/jpeg');
// Load
$thumb = imagecreatetruecolor($newwidth, $newheight);
$source = imagecreatefromjpeg($filename);
// Resize
imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width,
$height);
// Output
imagejpeg($thumb);
?>
imagecopyresampled
imagecopyresampled — Copy and resize part of an image with resampling
Description
imagecopyresampled ( resource $dst_image , resource $src_image , int $dst
_x , int $dst_y , int $src_x , int $src_y , int $dst_w , int $dst_h , int
$src_w , int $src_h ) : bool
If the source and destination coordinates and width and heights differ, appropriate
stretching or shrinking of the image fragment will be performed. The coordinates refer to
the upper left corner. This function can be used to copy regions within the same image
(if dst_image is the same as src_image) but if the regions overlap the results will be
unpredictable.
Parameters
dst_image-Destination image link resource.
dst_w-Destination width.
dst_h-Destination height.
src_w-Source width.
src_h-Source height.
Return Values
Examples
<?php
// The file
$filename = 'test.jpg';
$percent = 0.5;
// Content type
header('Content-Type: image/jpeg');
// Resample
$image_p = imagecreatetruecolor($new_width, $new_height);
$image = imagecreatefromjpeg($filename);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $wi
dth, $height);
// Output
imagejpeg($image_p, null, 100);
?>
This example will display an image with the maximum width, or height, of 200 pixels.
<?php
// The file
$filename = 'test.jpg';
// Content type
header('Content-Type: image/jpeg');
$ratio_orig = $width_orig/$height_orig;
// Resample
$image_p = imagecreatetruecolor($width, $height);
$image = imagecreatefromjpeg($filename);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig
, $height_orig);
// Output
imagejpeg($image_p, null, 100);
?>
Creating PDF files
To get started, you will need to download the FPDF class from the FPDF
Web site and include it in your PHP script like this:
require('fpdf.php');
Below is an example of how you can generate a simple PDF using FPDF.
$pdf->SetAuthor('ABC');
$pdf->SetTitle('FPDF tutorial');
Because we want to use the same font throughout the whole document, we can set
it before we create a page.
$pdf->SetFont('Helvetica','B',20);
$pdf->SetTextColor(50,60,100);
The SetFont function takes three parameters; the font family, style and size.
We are using Helvetica, Bold and 20 points, which will be applied to the
title of our document. You can either use one of the regular font families or
set up a different one using the AddFont () function.
With SetTextColor () we are also setting the font colour for the entire
document. The colours can be represented as RGB or grey scale. Here we
are using RGB values.
Now that that's done, let's set up a page for our PDF document.
$pdf->AddPage('P');
$pdf->SetDisplayMode(real,'default');
You can pass the AddPage () a parameter of "P" or "L" to specify the page
orientation. I've used "P" for portrait. The SetDisplayMode function
determines how the page will be displayed. You can pass it zoom and layout
parameters. Here we're using 100 percent zoom and the viewer's default
layout.
Now, that we've set up a page, let's insert an image to make it look nicer and
make it a link while we're at it. We'll display the FPDF logo by calling the
Image function and passing it the following parameters -- name of the file,
the dimensions and the URL.
$pdf->Image('logo.png',10,20,33,0,' ','http://www.fpdf.org/');
You could have also inserted the link with:
$pdf->SetXY(50,20);
$pdf->SetDrawColor(50,60,100);
$pdf->Cell(100,10,'FPDF Tutorial',1,0,'C',0);
The SetXY function sets the position of x and y coordinates, where we want
the title to appear.
SetDrawColor will set the colour of the border, using RGB values. After
that's done, we call the Cell function to print out a cell rectangle along with
the text of our title.
We are passing the function the following parameters; width, height, text,
border, ln, align and fill. The border is either 0 for no border or 1 for frame.
For ln we are using the default value 0, "C" to centre align the text inside it
and 0 for fill. Had we used 1 for fill the rectangle would have been coloured
in. With a value of 0 we are making it transparent.
Now we want to write the main text to the PDF, that is display a little
message.
$pdf->SetXY(10,50);
$pdf->SetFontSize(10);
$pdf->Write(5,'Congratulations! You have generated a PDF. ');
Again we are setting the x and y positions of the text, but this time we are
reducing the font size with the SetFontSize function. The write function will
print the text to a PDF. The parameter 5 will set the line height. This is only
relevant however, if there are multiple lines of text.
Finally we want to send the output to a given destination, using the Output
function.
$pdf->Output('example1.pdf','I');
Here we are passing the function the name of the file and the destination, in
this case "I". The "I" parameter will send the output to the browser.
Example
<?php
require(‘./fpdf.php’);
$pdf=new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
?>