Perl – Quick Guide ”; Previous Next Perl – Introduction Perl is a general-purpose programming language originally developed for text manipulation and now used for a wide range of tasks including system administration, web development, network programming, GUI development, and more. What is Perl? Perl is a stable, cross platform programming language. Though Perl is not officially an acronym but few people used it as Practical Extraction and Report Language. It is used for mission critical projects in the public and private sectors. Perl is an Open Source software, licensed under its Artistic License, or the GNU General Public License (GPL). Perl was created by Larry Wall. Perl 1.0 was released to usenet”s alt.comp.sources in 1987. At the time of writing this tutorial, the latest version of perl was 5.16.2. Perl is listed in the Oxford English Dictionary. PC Magazine announced Perl as the finalist for its 1998 Technical Excellence Award in the Development Tool category. Perl Features Perl takes the best features from other languages, such as C, awk, sed, sh, and BASIC, among others. Perls database integration interface DBI supports third-party databases including Oracle, Sybase, Postgres, MySQL and others. Perl works with HTML, XML, and other mark-up languages. Perl supports Unicode. Perl is Y2K compliant. Perl supports both procedural and object-oriented programming. Perl interfaces with external C/C++ libraries through XS or SWIG. Perl is extensible. There are over 20,000 third party modules available from the Comprehensive Perl Archive Network (CPAN). The Perl interpreter can be embedded into other systems. Perl and the Web Perl used to be the most popular web programming language due to its text manipulation capabilities and rapid development cycle. Perl is widely known as “the duct-tape of the Internet“. Perl can handle encrypted Web data, including e-commerce transactions. Perl can be embedded into web servers to speed up processing by as much as 2000%. Perl”s mod_perl allows the Apache web server to embed a Perl interpreter. Perl”s DBI package makes web-database integration easy. Perl is Interpreted Perl is an interpreted language, which means that your code can be run as is, without a compilation stage that creates a non portable executable program. Traditional compilers convert programs into machine language. When you run a Perl program, it”s first compiled into a byte code, which is then converted ( as the program runs) into machine instructions. So it is not quite the same as shells, or Tcl, which are strictly interpreted without an intermediate representation. It is also not like most versions of C or C++, which are compiled directly into a machine dependent format. It is somewhere in between, along with Python and awk and Emacs .elc files. Perl – Environment Before we start writing our Perl programs, let”s understand how to setup our Perl environment. Perl is available on a wide variety of platforms − Unix (Solaris, Linux, FreeBSD, AIX, HP/UX, SunOS, IRIX etc.) Win 9x/NT/2000/ WinCE Macintosh (PPC, 68K) Solaris (x86, SPARC) OpenVMS Alpha (7.2 and later) Symbian Debian GNU/kFreeBSD MirOS BSD And many more… This is more likely that your system will have perl installed on it. Just try giving the following command at the $ prompt − $perl -v If you have perl installed on your machine, then you will get a message something as follows − This is perl 5, version 16, subversion 2 (v5.16.2) built for i686-linux Copyright 1987-2012, Larry Wall Perl may be copied only under the terms of either the Artistic License or the GNU General Public License, which may be found in the Perl 5 source kit. Complete documentation for Perl, including FAQ lists, should be found on this system using “man perl” or “perldoc perl”. If you have access to the Internet, point your browser at http://www.perl.org/, the Perl Home Page. If you do not have perl already installed, then proceed to the next section. Getting Perl Installation The most up-to-date and current source code, binaries, documentation, news, etc. are available at the official website of Perl. Perl Official Website − https://www.perl.org/ You can download Perl documentation from the following site. Perl Documentation Website − https://perldoc.perl.org Install Perl Perl distribution is available for a wide variety of platforms. You need to download only the binary code applicable for your platform and install Perl. If the binary code for your platform is not available, you need a C compiler to compile the source code manually. Compiling the source code offers more flexibility in terms of choice of features that you require in your installation. Here is a quick overview of installing Perl on various platforms. Unix and Linux Installation Here are the simple steps to install Perl on Unix/Linux machine. Open a Web browser and go to https://www.perl.org/get.html. Follow the link to download zipped source code available for Unix/Linux. Download perl-5.x.y.tar.gz file and issue the following commands at $ prompt. $tar -xzf perl-5.x.y.tar.gz $cd perl-5.x.y $./Configure -de $make $make test $make install NOTE − Here $ is a Unix prompt where you type your command, so make sure you are not typing $ while typing the above mentioned commands. This will install Perl in a standard location /usr/local/bin and its libraries are installed in /usr/local/lib/perlXX, where XX is the version of Perl that you are using. It will take a while to compile the source code after issuing the make command. Once installation is done, you can issue perl -v command at $ prompt to check perl installation. If everything is fine, then it will display message like we have shown above. Windows Installation Here are the steps to install Perl on Windows machine. Follow the link for the Strawberry Perl installation on Windows http://strawberryperl.com Download either 32bit or 64bit version of installation. Run the downloaded file by double-clicking it in Windows Explorer. This brings up the Perl install wizard, which is really easy to use. Just accept the default settings, wait until the installation is finished, and you”re ready to roll! Macintosh Installation In order to build your own version of
Category: Computer Programming
Perl – Socket Programming
Perl – Socket Programming ”; Previous Next What is a Socket? Socket is a Berkeley UNIX mechanism of creating a virtual duplex connection between different processes. This was later ported on to every known OS enabling communication between systems across geographical location running on different OS software. If not for the socket, most of the network communication between systems would never ever have happened. Taking a closer look; a typical computer system on a network receives and sends information as desired by the various applications running on it. This information is routed to the system, since a unique IP address is designated to it. On the system, this information is given to the relevant applications, which listen on different ports. For example an internet browser listens on port 80 for information received from the web server. Also we can write our custom applications which may listen and send/receive information on a specific port number. For now, let”s sum up that a socket is an IP address and a port, enabling connection to send and recieve data over a network. To explain above mentioned socket concept we will take an example of Client – Server Programming using Perl. To complete a client server architecture we would have to go through the following steps − To Create a Server Create a socket using socket call. Bind the socket to a port address using bind call. Listen to the socket at the port address using listen call. Accept client connections using accept call. To Create a Client Create a socket with socket call. Connect (the socket) to the server using connect call. Following diagram shows the complete sequence of the calls used by Client and Server to communicate with each other − Server Side Socket Calls The socket() call The socket() call is the first call in establishing a network connection is creating a socket. This call has the following syntax − socket( SOCKET, DOMAIN, TYPE, PROTOCOL ); The above call creates a SOCKET and other three arguments are integers which should have the following values for TCP/IP connections. DOMAIN should be PF_INET. It”s probable 2 on your computer. TYPE should be SOCK_STREAM for TCP/IP connection. PROTOCOL should be (getprotobyname(”tcp”))[2]. It is the particular protocol such as TCP to be spoken over the socket. So socket function call issued by the server will be something like this − use Socket # This defines PF_INET and SOCK_STREAM socket(SOCKET,PF_INET,SOCK_STREAM,(getprotobyname(”tcp”))[2]); The bind() call The sockets created by socket() call are useless until they are bound to a hostname and a port number. Server uses the following bind() function to specify the port at which they will be accepting connections from the clients. bind( SOCKET, ADDRESS ); Here SOCKET is the descriptor returned by socket() call and ADDRESS is a socket address ( for TCP/IP ) containing three elements − The address family (For TCP/IP, that”s AF_INET, probably 2 on your system). The port number (for example 21). The internet address of the computer (for example 10.12.12.168). As the bind() is used by a server, which does not need to know its own address so the argument list looks like this − use Socket # This defines PF_INET and SOCK_STREAM $port = 12345; # The unique port used by the sever to listen requests $server_ip_address = “10.12.12.168”; bind( SOCKET, pack_sockaddr_in($port, inet_aton($server_ip_address))) or die “Can”t bind to port $port! n”; The or die clause is very important because if a server dies without outstanding connections, the port won”t be immediately reusable unless you use the option SO_REUSEADDR using setsockopt() function. Here pack_sockaddr_in() function is being used to pack the Port and IP address into binary format. The listen() call If this is a server program, then it is required to issue a call to listen() on the specified port to listen, i.e., wait for the incoming requests. This call has the following syntax − listen( SOCKET, QUEUESIZE ); The above call uses SOCKET descriptor returned by socket() call and QUEUESIZE is the maximum number of outstanding connection request allowed simultaneously. The accept() call If this is a server program then it is required to issue a call to the access() function to accept the incoming connections. This call has the following syntax − accept( NEW_SOCKET, SOCKET ); The accept call receive SOCKET descriptor returned by socket() function and upon successful completion, a new socket descriptor NEW_SOCKET is returned for all future communication between the client and the server. If access() call fails, then it returns FLASE which is defined in Socket module which we have used initially. Generally, accept() is used in an infinite loop. As soon as one connection arrives the server either creates a child process to deal with it or serves it himself and then goes back to listen for more connections. while(1) { accept( NEW_SOCKET, SOCKT ); ……. } Now all the calls related to server are over and let us see a call which will be required by the client. Client Side Socket Calls The connect() call If you are going to prepare client program, then first you will use socket() call to create a socket and then you would have to use connect() call to connect to the server. You already have seen socket() call syntax and it will remain similar to server socket() call, but here is the syntax for connect() call − connect( SOCKET, ADDRESS ); Here SCOKET is the socket descriptor returned by socket() call issued by the client and ADDRESS is a socket address similar to bind call, except that it contains the IP address of the remote server. $port = 21; # For example, the ftp port $server_ip_address = “10.12.12.168”; connect( SOCKET, pack_sockaddr_in($port, inet_aton($server_ip_address))) or die “Can”t connect to port $port! n”; If you connect to the server successfully, then you can start sending your commands to the server using SOCKET descriptor, otherwise your client will come out by giving an error message. Client – Server Example Following is a Perl code to
Perl – CGI Programming
Perl – CGI Programming ”; Previous Next What is CGI ? A Common Gateway Interface, or CGI, is a set of standards that defines how information is exchanged between the web server and a custom script. The CGI specs are currently maintained by the NCSA and NCSA defines CGI is as follows − The Common Gateway Interface, or CGI, is a standard for external gateway programs to interface with information servers such as HTTP servers. The current version is CGI/1.1 and CGI/1.2 is under progress. Web Browsing To understand the concept of CGI, lets see what happens when we click a hyper link available on a web page to browse a particular web page or URL. Your browser contacts web server using HTTP protocol and demands for the URL, i.e., web page filename. Web Server will check the URL and will look for the filename requested. If web server finds that file then it sends the file back to the browser without any further execution otherwise sends an error message indicating that you have requested a wrong file. Web browser takes response from web server and displays either the received file content or an error message in case file is not found. However, it is possible to set up HTTP server in such a way so that whenever a file in a certain directory is requested that file is not sent back; instead it is executed as a program, and whatever that program outputs as a result, that is sent back for your browser to display. This can be done by using a special functionality available in the web server and it is called Common Gateway Interface or CGI and such programs which are executed by the server to produce final result, are called CGI scripts. These CGI programs can be a PERL Script, Shell Script, C or C++ program, etc. CGI Architecture Diagram Web Server Support and Configuration Before you proceed with CGI Programming, make sure that your Web Server supports CGI functionality and it is configured to handle CGI programs. All the CGI programs to be executed by the web server are kept in a pre-configured directory. This directory is called CGI directory and by convention it is named as /cgi-bin. By convention Perl CGI files will have extention as .cgi. First CGI Program Here is a simple link which is linked to a CGI script called hello.cgi. This file has been kept in /cgi-bin/ directory and it has the following content. Before running your CGI program, make sure you have change mode of file using chmod 755 hello.cgi UNIX command. #!/usr/bin/perl print “Content-type:text/htmlrnrn”; print ”<html>”; print ”<head>”; print ”<title>Hello Word – First CGI Program</title>”; print ”</head>”; print ”<body>”; print ”<h2>Hello Word! This is my first CGI program</h2>”; print ”</body>”; print ”</html>”; 1; Now if you click hello.cgi link then request goes to web server who search for hello.cgi in /cgi-bin directory, execute it and whatever result got generated, web server sends that result back to the web browser, which is as follows − Hello Word! This is my first CGI program This hello.cgi script is a simple Perl script which is writing its output on STDOUT file, i.e., screen. There is one important and extra feature available which is first line to be printed Content-type:text/htmlrnrn. This line is sent back to the browser and specifies the content type to be displayed on the browser screen. Now you must have undertood basic concept of CGI and you can write many complicated CGI programs using Perl. This script can interact with any other exertnal system also to exchange information such as a database, web services, or any other complex interfaces. Understanding HTTP Header The very first line Content-type:text/htmlrnrn is a part of HTTP header, which is sent to the browser so that browser can understand the incoming content from server side. All the HTTP header will be in the following form − HTTP Field Name: Field Content For Example − Content-type:text/htmlrnrn There are few other important HTTP headers, which you will use frequently in your CGI Programming. Sr.No. Header & Description 1 Content-type: String A MIME string defining the format of the content being returned. Example is Content-type:text/html 2 Expires: Date String The date when the information becomes invalid. This should be used by the browser to decide when a page needs to be refreshed. A valid date string should be in the format 01 Jan 1998 12:00:00 GMT. 3 Location: URL String The URL that should be returned instead of the URL requested. You can use this filed to redirect a request to any other location. 4 Last-modified: String The date of last modification of the file. 5 Content-length: String The length, in bytes, of the data being returned. The browser uses this value to report the estimated download time for a file. 6 Set-Cookie: String Set the cookie passed through the string CGI Environment Variables All the CGI program will have access to the following environment variables. These variables play an important role while writing any CGI program. Sr.No. Variables Names & Description 1 CONTENT_TYPE The data type of the content. Used when the client is sending attached content to the server. For example file upload, etc. 2 CONTENT_LENGTH The length of the query information. It”s available only for POST requests 3 HTTP_COOKIE Returns the set cookies in the form of key & value pair. 4 HTTP_USER_AGENT The User-Agent request-header field contains information about the user agent originating the request. Its name of the web browser. 5 PATH_INFO The path for the CGI script. 6 QUERY_STRING The URL-encoded information that is sent with GET method request. 7 REMOTE_ADDR The IP address of the remote host making the request. This can be useful for logging or for authentication purpose. 8 REMOTE_HOST The fully qualified name of the host making the request. If this information is not available then REMOTE_ADDR can be used to get IR address. 9 REQUEST_METHOD The method used to make the
Simulation Of Sketches
PHP ImageMagick – Simulation Of Sketches ”; Previous Next In this chapter, you will be learning to simulate different types of sketches using a few inbuilt functions provided by Imagemagick. Simulating a Charcoal Drawing ImageMagick provided a method called ‘charcoalImage()’ which produces the charcoal drawing of the input image. Syntax public Imagick::charcoalImage(float $radius, float $sigma): bool This function takes 2 parameters: radius and sigma. Radius is a float value that specifies the radius of the Gaussian (in pixels), not counting the center pixel. Sigma is also a float value that specifies the standard deviation of the Gaussian, in pixels. Example This is an example which shows the implementation of ‘charcoalImage()’ function. At first, a new imagick object is created and an image is taken as input. Then, ‘charcoalImage()’ function is applied on that image. The required output is obtained in the form of ‘charcoalImage.png’. <?php $image=new Imagick($_SERVER[”DOCUMENT_ROOT”].”/test/image.png”); $image->charcoalImage(2, 2); $image->writeImage($_SERVER[”DOCUMENT_ROOT”].”/test/charcoalImage.png”); ?> Assume that the following is the input image (image.png) in the program − Output Simulating a Pencil Sketch There is an inbuilt function called ‘sketchImage()’ provided by Imagemagick which produces the pencil sketch of the input image. Syntax public Imagick::sketchImage(float $radius, float $sigma, float $angle): bool This function consists of 3 parameters: radius, sigma, and angle. These are float values. ‘Radius’ specifies the radius of the Gaussian (in pixels), ‘sigma’ specifies the standard deviation of the Gaussian (in pixels) and ‘angle’ specifies the angle by which the effect must be applied and specifies the angle of the blurring motion. Example This is an example which shows the implementation of ‘sketchImage()’ function. At first, a new imagick object is created and an image is taken as input. Then, ‘sketchImage()’ function is applied on that image. The required output is obtained in the form of ‘sketchImage.png’. <?php $image=new Imagick($_SERVER[”DOCUMENT_ROOT”].”/test/image.png”); $image->sketchImage(11, 11, 30); $image->writeImage($_SERVER[”DOCUMENT_ROOT”].”/test/sketchImage.png”); ?> Assume that the following is the input image (image.png) in the program − Output Simulating an Oil Painting Oil painting is a type of painting produced using oil-based paints. Without using oil paints in real, this oil painting can be simulated using an inbuilt function ‘oilPaintImage()’ of Imagemagick in PHP. Syntax public Imagick::oilPaintImage(float $radius): bool This function contains only one parameter which is ‘radius’ which is a float value. It specifies the radius of the circular neighborhood. This function takes an image as input and applies a special effect filter that simulates an oil painting and produces that as output. Example This is an example which shows the implementation of ‘oilPaintImage()’ function. At first, a new imagick object is created and an image is taken as input. Then, ‘oilPaintImage()’ function is applied on that image. The required output is obtained in the form of ‘oilPaintImage.png’. <?php $image=new Imagick($_SERVER[”DOCUMENT_ROOT”].”/test/image.png”); $image->oilPaintImage(2); $image->writeImage($_SERVER[”DOCUMENT_ROOT”].”/test/oilPaintImage.png”); ?> Assume that the following is the input image (image.png) in the program − Output Print Page Previous Next Advertisements ”;
Splicing & Spreading
PHP ImageMagick – Splicing & Spreading ”; Previous Next In this chapter, you will be learning to spread an image and splice an image using a few inbuilt functions of Imagemagick. Image Spreading In this section, you will be learning to spread an image easily using the ‘spreadImage()’ function provided by Imagemagick. Spreading an image is randomly displacing each pixel in a block. Syntax public Imagick::spreadImage(float $radius): bool This function takes in only one parameter: radius. ‘Radius’ is a float value that specifies the value to displace each pixel in a block. Example In the below example, an imagick object is created and an image is taken as input. Now, ‘spreadImage()’ function is applied on the image with a single parameter(radius=5). Then, the final image is displayed as output. <?php $image=new Imagick($_SERVER[”DOCUMENT_ROOT”].”/test/imagee.png”); $image->spreadImage(5); $image->writeImage($_SERVER[”DOCUMENT_ROOT”].”/test/spreadImage.png”); ?> Assume that the following is the input image (image.png) in the program − Output Image Splicing In this chapter, you will be learning to splice a solid color into the image using an inbuilt function named ‘spliceImage()’ in Imagemagick. This function takes an image as input, and splices a solid color into the image with the specified parameters (dimensions and positions of the splice). Syntax public Imagick::spliceImage( int $width, int $height, int $x, int $y ): bool This function contains 4 parameters: width, height, x, and y. ‘Width’ and ‘height’ are integer values that specify the width and height of the splice respectively. ‘x’ and ‘y’ are also integer values that specify the position on the X-axis and Y-axis respectively. Example In the below example, an imagick object is created and image is taken as input. On that image, ‘spliceImage()’ function is applied with the parameters (width=50, height=100, x=100, y=50). Then, the image after splicing is obtained as output. <?php $image=new Imagick($_SERVER[”DOCUMENT_ROOT”].”/test/image.png”); $image->spliceImage(50, 100, 100, 50); $image->writeImage($_SERVER[”DOCUMENT_ROOT”].”/test/spliceImage.png”); ?> Assume that the following is the input image (image.png) in the program − Output Print Page Previous Next Advertisements ”;
Perl – Object Oriented
Object Oriented Programming in PERL ”; Previous Next We have already studied references in Perl and Perl anonymous arrays and hashes. Object Oriented concept in Perl is very much based on references and anonymous array and hashes. Let”s start learning basic concepts of Object Oriented Perl. Object Basics There are three main terms, explained from the point of view of how Perl handles objects. The terms are object, class, and method. An object within Perl is merely a reference to a data type that knows what class it belongs to. The object is stored as a reference in a scalar variable. Because a scalar only contains a reference to the object, the same scalar can hold different objects in different classes. A class within Perl is a package that contains the corresponding methods required to create and manipulate objects. A method within Perl is a subroutine, defined with the package. The first argument to the method is an object reference or a package name, depending on whether the method affects the current object or the class. Perl provides a bless() function, which is used to return a reference which ultimately becomes an object. Defining a Class It is very simple to define a class in Perl. A class is corresponding to a Perl Package in its simplest form. To create a class in Perl, we first build a package. A package is a self-contained unit of user-defined variables and subroutines, which can be re-used over and over again. Perl Packages provide a separate namespace within a Perl program which keeps subroutines and variables independent from conflicting with those in other packages. To declare a class named Person in Perl we do − package Person; The scope of the package definition extends to the end of the file, or until another package keyword is encountered. Creating and Using Objects To create an instance of a class (an object) we need an object constructor. This constructor is a method defined within the package. Most programmers choose to name this object constructor method new, but in Perl you can use any name. You can use any kind of Perl variable as an object in Perl. Most Perl programmers choose either references to arrays or hashes. Let”s create our constructor for our Person class using a Perl hash reference. When creating an object, you need to supply a constructor, which is a subroutine within a package that returns an object reference. The object reference is created by blessing a reference to the package”s class. For example − package Person; sub new { my $class = shift; my $self = { _firstName => shift, _lastName => shift, _ssn => shift, }; # Print all the values just for clarification. print “First Name is $self->{_firstName}n”; print “Last Name is $self->{_lastName}n”; print “SSN is $self->{_ssn}n”; bless $self, $class; return $self; } Now Let us see how to create an Object. $object = new Person( “Mohammad”, “Saleem”, 23234345); You can use simple hash in your consturctor if you don”t want to assign any value to any class variable. For example − package Person; sub new { my $class = shift; my $self = {}; bless $self, $class; return $self; } Defining Methods Other object-oriented languages have the concept of security of data to prevent a programmer from changing an object data directly and they provide accessor methods to modify object data. Perl does not have private variables but we can still use the concept of helper methods to manipulate object data. Lets define a helper method to get person’s first name − sub getFirstName { return $self->{_firstName}; } Another helper function to set person’s first name − sub setFirstName { my ( $self, $firstName ) = @_; $self->{_firstName} = $firstName if defined($firstName); return $self->{_firstName}; } Now lets have a look into complete example: Keep Person package and helper functions into Person.pm file. #!/usr/bin/perl package Person; sub new { my $class = shift; my $self = { _firstName => shift, _lastName => shift, _ssn => shift, }; # Print all the values just for clarification. print “First Name is $self->{_firstName}n”; print “Last Name is $self->{_lastName}n”; print “SSN is $self->{_ssn}n”; bless $self, $class; return $self; } sub setFirstName { my ( $self, $firstName ) = @_; $self->{_firstName} = $firstName if defined($firstName); return $self->{_firstName}; } sub getFirstName { my( $self ) = @_; return $self->{_firstName}; } 1; Now let”s make use of Person object in employee.pl file as follows − #!/usr/bin/perl use Person; $object = new Person( “Mohammad”, “Saleem”, 23234345); # Get first name which is set using constructor. $firstName = $object->getFirstName(); print “Before Setting First Name is : $firstNamen”; # Now Set first name using helper function. $object->setFirstName( “Mohd.” ); # Now get first name set by helper function. $firstName = $object->getFirstName(); print “Before Setting First Name is : $firstNamen”; When we execute above program, it produces the following result − First Name is Mohammad Last Name is Saleem SSN is 23234345 Before Setting First Name is : Mohammad Before Setting First Name is : Mohd. Inheritance Object-oriented programming has very good and useful concept called inheritance. Inheritance simply means that properties and methods of a parent class will be available to the child classes. So you don”t have to write the same code again and again, you can just inherit a parent class. For example, we can have a class Employee, which inherits from Person. This is referred to as an “isa” relationship because an employee is a person. Perl has a special variable, @ISA, to help with this. @ISA governs (method) inheritance. Following are the important points to be considered while using inheritance − Perl searches the class of the specified object for the given method or attribute, i.e., variable. Perl searches the classes defined in the object class”s @ISA array. If no method is found in steps 1 or 2, then Perl uses an AUTOLOAD subroutine, if one is found in the @ISA tree. If a matching method still cannot be found, then
Composite Images
PHP ImageMagick – Composite Images ”; Previous Next The combination of two or more images to create a new one is called composite photography. And the combined photo is called a composite image. Combining visual elements from separate sources into a single image is often done to create the illusion that all those elements are parts of the same image. Doing this manually becomes a very complex task and it takes hours. To make this process easy and fast, Imagemagick has provided a method named ‘compositeImage()’ which takes two images as input and provides the combined image as output. Syntax public Imagick::compositeImage(Imagick $composite_object, int $composite, int $x, int $y, int $channel = Imagick::CHANNEL_DEFAULT): bool The parameters of this method are composite_object, x, y, and channel. ‘Composite_object’ is an Imagick object which holds the composite image. ‘x’ is the column offset of the composited image and ‘y’ is the row offset of the composited image. ‘Channel’ provides any channel constant that is valid for your channel mode. Example This example is a PHP code snippet which implements ‘compositeImage()’ function. Firstly, two imagick objects are created and two images are taken as inputs. Both the images are composited with the help of ‘compositeImage()’ function, and the output image is in the format ‘compositeImage.png’. <?php $image1=new Imagick($_SERVER[”DOCUMENT_ROOT”].”/test/image1.jpg”); $image2=new Imagick($_SERVER[”DOCUMENT_ROOT”].”/test/image2.jpg”); $image1->setImageVirtualPixelMethod(Imagick::VIRTUALPIXELMETHOD_TRANSPARENT); $image1->setImageArtifact(”compose:args”, “1,0,-0.5,0.5″); $image1->compositeImage($image2, Imagick::COMPOSITE_MATHEMATICS, 0, 0); $image1->writeImage($_SERVER[”DOCUMENT_ROOT”].”/test/compositeImage.png”); ?> Assume that the following is the input image (image1.jpg) in the program − Assume that the following is the input image (image2.jpg) in the program − Output Print Page Previous Next Advertisements ”;
Perl – Sending Email
Perl – Sending Email ”; Previous Next Using sendmail Utility Sending a Plain Message If you are working on Linux/Unix machine then you can simply use sendmail utility inside your Perl program to send email. Here is a sample script that can send an email to a given email ID. Just make sure the given path for sendmail utility is correct. This may be different for your Linux/Unix machine. #!/usr/bin/perl $to = ”[email protected]”; $from = ”[email protected]”; $subject = ”Test Email”; $message = ”This is test email sent by Perl Script”; open(MAIL, “|/usr/sbin/sendmail -t”); # Email Header print MAIL “To: $ton”; print MAIL “From: $fromn”; print MAIL “Subject: $subjectnn”; # Email Body print MAIL $message; close(MAIL); print “Email Sent Successfullyn”; Actually, the above script is a client email script, which will draft email and submit to the server running locally on your Linux/Unix machine. This script will not be responsible for sending email to actual destination. So you have to make sure email server is properly configured and running on your machine to send email to the given email ID. Sending an HTML Message If you want to send HTML formatted email using sendmail, then you simply need to add Content-type: text/htmln in the header part of the email as follows − #!/usr/bin/perl $to = ”[email protected]”; $from = ”[email protected]”; $subject = ”Test Email”; $message = ”<h1>This is test email sent by Perl Script</h1>”; open(MAIL, “|/usr/sbin/sendmail -t”); # Email Header print MAIL “To: $ton”; print MAIL “From: $fromn”; print MAIL “Subject: $subjectnn”; print MAIL “Content-type: text/htmln”; # Email Body print MAIL $message; close(MAIL); print “Email Sent Successfullyn”; Using MIME::Lite Module If you are working on windows machine, then you will not have access on sendmail utility. But you have alternate to write your own email client using MIME:Lite perl module. You can download this module from MIME-Lite-3.01.tar.gz and install it on your either machine Windows or Linux/Unix. To install it follow the simple steps − $tar xvfz MIME-Lite-3.01.tar.gz $cd MIME-Lite-3.01 $perl Makefile.PL $make $make install That”s it and you will have MIME::Lite module installed on your machine. Now you are ready to send your email with simple scripts explained below. Sending a Plain Message Now following is a script which will take care of sending email to the given email ID − #!/usr/bin/perl use MIME::Lite; $to = ”[email protected]”; $cc = ”[email protected]”; $from = ”[email protected]”; $subject = ”Test Email”; $message = ”This is test email sent by Perl Script”; $msg = MIME::Lite->new( From => $from, To => $to, Cc => $cc, Subject => $subject, Data => $message ); $msg->send; print “Email Sent Successfullyn”; Sending an HTML Message If you want to send HTML formatted email using sendmail, then you simply need to add Content-type: text/htmln in the header part of the email. Following is the script, which will take care of sending HTML formatted email − #!/usr/bin/perl use MIME::Lite; $to = ”[email protected]”; $cc = ”[email protected]”; $from = ”[email protected]”; $subject = ”Test Email”; $message = ”<h1>This is test email sent by Perl Script</h1>”; $msg = MIME::Lite->new( From => $from, To => $to, Cc => $cc, Subject => $subject, Data => $message ); $msg->attr(“content-type” => “text/html”); $msg->send; print “Email Sent Successfullyn”; Sending an Attachment If you want to send an attachment, then following script serves the purpose − #!/usr/bin/perl use MIME::Lite; $to = ”[email protected]”; $cc = ”[email protected]”; $from = ”[email protected]”; $subject = ”Test Email”; $message = ”This is test email sent by Perl Script”; $msg = MIME::Lite->new( From => $from, To => $to, Cc => $cc, Subject => $subject, Type => ”multipart/mixed” ); # Add your text message. $msg->attach(Type => ”text”, Data => $message ); # Specify your file as attachement. $msg->attach(Type => ”image/gif”, Path => ”/tmp/logo.gif”, Filename => ”logo.gif”, Disposition => ”attachment” ); $msg->send; print “Email Sent Successfullyn”; You can attach as many files as you like in your email using attach() method. Using SMTP Server If your machine is not running an email server then you can use any other email server available at the remote location. But to use any other email server you will need to have an id, its password, URL, etc. Once you have all the required information, you simple need to provide that information in send() method as follows − $msg->send(”smtp”, “smtp.myisp.net”, AuthUser=>”id”, AuthPass=>”password” ); You can contact your email server administrator to have the above used information and if a user id and password is not already available then your administrator can create it in minutes. Print Page Previous Next Advertisements ”;
PHP ImageMagick – Home
PHP ImageMagick Tutorial PDF Version Quick Guide Resources Job Search Discussion Imagick is a PHP extension that allows us to use the ImageMagick API to create and edit images. ImageMagick is a bitmap image creation, editing, and composition software suite. DPX, EXR, GIF, JPEG, JPEG-2000, PDF, PhotoCD, PNG, Postscript, SVG, and TIFF are among the formats it can read, convert, and write. It is used for file format conversion, color quantization, liquid rescaling, dithering, and many artistic effects.. Audience This tutorial is designed for those learners who wish to acquire knowledge and understand the Imagick which is a PHP extension of Imagemagick API. Prerequisites This tutorial focuses on the Imagick which is the PHP extension of Imagemagick. So, we assume that the readers of this tutorial have basic knowledge of PHP. Previous Page Next Page Print Page Previous Next Advertisements ”;
Rotation and Rolling
PHP ImageMagick – Rotation and Rolling ”; Previous Next In this chapter, you will be learning to rotate and roll images using the inbuilt functions of Imagemagick. Rotating an image Imagemagick has provided an inbuilt function ‘rotateImage()’ which is used to rotate the images according to the angle specified. This function takes an image as input, applied this function, and rotates the image and the rotated image is obtained as output. Syntax public Imagick::rotateImage(mixed $background, float $degrees): bool This function has 2 parameters: background and degrees. ‘Background’ specifies the background color and ‘degrees’ is a float value that specifies the rotation angle, in degrees. The image is rotated clockwise at the specified angle. Example In the below example, a new imagick object is created at first and an image is taken as input. ‘rotateImage()’ function is applied on that image and the image is rotated to that specified angle. The rotated image is obtained as output with the help of ‘writeImage()’ function. <?php $image=new Imagick($_SERVER[”DOCUMENT_ROOT”].”/test/image.png”); $image->rotateImage(”black”, 40); $image->writeImage($_SERVER[”DOCUMENT_ROOT”].”/test/rotateImage.png”); ?> Assume that the following is the input image (image.png) in the program − Output Rolling an image Did you ever observe the process of rolling something? That thing that you are rolling is moved by revolving or turning it over and over. Rolling an image also means the same. It is nothing but offsetting an image. For this purpose, ImageMagick has provided an inbuilt function ‘rollImage()’ which takes an image as input, rolls the image and the rolled image is obtained as output. Syntax public Imagick::rollImage(int $x, int $y): bool This function takes 2 parameters: x and y. ‘x’ and ‘y’ are integer values, and they specify the x offset and y offset respectively. Example In this example, an image is taken as input by creating a new imagick object. Then, ‘rollImage()’ function is applied on it with the help of specified a and y offsets (x=30, y=40). The rolled image is obtained as output. <?php $image=new Imagick($_SERVER[”DOCUMENT_ROOT”].”/test/image.png”); $image->rollImage (300, 40); $image->writeImage($_SERVER[”DOCUMENT_ROOT”].”/test/rollImage.png”); ?> Assume that the following is the input image (image.png) in the program − Output Print Page Previous Next Advertisements ”;