Creating image using php

How to Create an Image in PHP

PHP makes it very easy to do many things needed on a website, among which is to create an image. The ability to generate an image in PHP can be useful if you want to do things like create CAPTCHA images, or even design a banner or logo on the fly the way some free blogging software do.

By the end of this tutorial, you will be able to create or modify an existing image using PHP, set the colours («colors» if you use a different variant of English) of its background, the text and the lines you draw, write text to that image, draw a line and set its thickness. You will also be able to either send that image to a web browser or to save it as a file. Armed with this basic foundation, you will also be able to knowledgeably explore further and perform more complex operations on images using PHP if you wish.

Читайте также:  Create slideshow with javascript

Prerequisites

Note: If you are here looking for an article on how to create banners or logos for your website, and not strictly for an article on how to write PHP scripts to generate such images, you may find my article on How to Create a Logo for Your Site the Quick and Easy Way more relevant.

Basic PHP Knowledge

Your PHP Must Have Been Compiled with the GD Library

FreeType Must Be Compiled for TrueType Font Support

An Introduction to Creating an Image from Scratch Using PHP

The easiest way to understand how to create an image is by looking at some sample code.

$my_img = imagecreate( 200, 80 );
$background = imagecolorallocate( $my_img, 0, 0, 255 );
$text_colour = imagecolorallocate( $my_img, 255, 255, 0 );
$line_colour = imagecolorallocate( $my_img, 128, 255, 0 );
imagestring( $my_img, 4, 30, 25, «thesitewizard.com», $text_colour );
imagesetthickness ( $my_img, 5 );
imageline( $my_img, 30, 45, 165, 45, $line_colour );

header( «Content-type: image/png» );
imagepng( $my_img );
imagecolordeallocate( $line_color );
imagecolordeallocate( $text_color );
imagecolordeallocate( $background );
imagedestroy( $my_img );
?>

The above code creates a 200×80 PNG image with a blue background and yellow text. It can be called from within your web page simply by referencing the php file. For example, if the PHP file that contains the above code is called myimage.php , then the HTML code to invoke it can simply be:

Image created by a PHP script

Explanation of the Code

Creating the Image

Using Colours in PHP

Writing Text to the Image

Drawing a Line and Setting the Thickness of the Brush

How to Output the Image

Since the output of my example script is the image itself, I send an «image/png» content type header to the browser telling it that what follows are the bytes of a PNG image. The function imagepng() is then called to generate the necessary image from my $my_img image identifer. Since I called imagepng() without a second parameter, the function automatically sends its output to the browser. If you prefer to save your image, don’t call the header() function to output the header, and call imagepng() with the filename of the image for its second parameter, like the following:

Freeing Resources

Modifying an Existing Image

In most cases, creating an image from scratch is overkill. For most web purposes, you can usually design the basic background of your image using a normal image editor and only add any additional text or graphical elements that need to be dynamically drawn using PHP. This allows you to speed up your scripts and reduce the resource consumption on your web server. It also lets you create your picture using professional picture designing tools.

To use an existing GIF, JPEG or PNG image as a canvas on which you add additional elements, use one of the following functions instead of imagecreate() .

  • imagecreatefromgif ( string $filename )
  • imagecreatefromjpeg ( string $filename )
  • imagecreatefrompng ( string $filename )

For example, if you created a GIF file called «mytemplate.gif», the function can be called as follows:

Like the basic imagecreate() function, these functions return FALSE if they fail to load the image for any reason.

Using TrueType Fonts

If you want to use a True Type font, you will need to use imagettftext() instead. For details on how to use this function, please consult the function’s manual page on php.net.

You should note a few things, though, before using this function:

  • Check that your web host has compiled FreeType support into PHP before you rely on this function.
  • Find out whether your web host’s PHP is using GD version 1 or 2. This affects a number of things, including the meaning of the font size parameter to the function (whether it means pixel size or point size).
  • Note that the coordinates for the text has a different starting point from imagestring() . That is, a coordinate like (say) 10,20 has a different meaning in the two functions.
  • Make sure the font you want exists on your web server. Remember that your web server is not the same as your computer. Just because a font like Arial exists on your computer does not mean that it exists on your server. If you have fonts that you created yourself, you may want to upload those to your web directory and use those instead. At least, that way, you have a guarantee that the font needed by your script exists.
  • The path setting to the font file is tricky, and depends on the version of the GD library your web server is using. One way around it is to specify the full path to the file on your server.

Drawing to Your Image

Besides the line drawing function used above, PHP has other functions that you can use. A complete list of functions, along with their descriptions, can be found on http://www.php.net/gd. To whet your appetite, functions include those that allow you to draw ellipses, arcs and polygons, change the style of your lines (to say dashed lines), and so on.

However, unless you have special reasons why you might want to dynamically draw complex pictures onto an image, you should consider creating your base image using a normal picture editor, load that image using a function like imagecreatefrompng() , and then only modifying small details with your script. Generating everything from scratch is unnecessary for most purposes, and can drain your web server resources.

Conclusion

Congratulations. You can now write scripts that create and output images, write text to those images, set the brush thickness for lines and draw those lines. You also have enough basic knowledge to intelligently explore further the other facilities available in PHP to design and modify your images.

Copyright © 2008-2018 by Christopher Heng. All rights reserved.
Get more free tips and articles like this, on web design, promotion, revenue and scripting, from https://www.thesitewizard.com/.

thesitewizard™ News Feed (RSS Site Feed)

Do you find this article useful? You can learn of new articles and scripts that are published on thesitewizard.com by subscribing to the RSS feed. Simply point your RSS feed reader or a browser that supports RSS feeds at https://www.thesitewizard.com/thesitewizard.xml. You can read more about how to subscribe to RSS site feeds from my RSS FAQ.

Please Do Not Reprint This Article

This article is copyrighted. Please do not reproduce or distribute this article in whole or part, in any form.

New Articles

It will appear on your page as:

Copyright © 2008-2018 by Christopher Heng. All rights reserved.
thesitewizard™, thefreecountry™ and HowToHaven™ are trademarks of Christopher Heng.
This page was last updated on 13 April 2018.

Источник

How to generate an image: using PHP GD Library. (part 1)

photo by Christiana Morillo from Pexels: https://www.pexels.com/photo/close-up-photo-of-person-typing-on-laptop-1181675/

PHP GD is a library that performs fantastic tasks that helps you to do several things with your image. As a PHP Developer, There are times when you have to survey into some advance functionality of your stack. And one is the GD library, is not easily done by most developers.
and it helps you do anything with image. If you’re ready, let’s proceed to this PHP amazing library that helps you generate, and draw an image.

What is GD Library

GD is an acronym that stands for “GRAPHIC DRAW”. The GD library in PHP enables you to create image data, and it’s the most used image processing tool in PHP. GD was originally developed by Thomas Boutell. By far it is a powerful image-processing library for PHP (it is also available for other languages like Perl). GD library allows you to dynamically create and edit of images, charts thumbnails, etc. The following file type that can be created or edited using the GD library, are GIF, JPEG, and PNG.

How Does GD Library work

One thing you should understand is that the GD library has a pattern in which it works. Now if you don’t follow the process of the GD library you won’t see anything on your interface. Below are the steps for implementing GD library in your project: Step 1:
You must check if the GD library is enabled in your system local server (XAMMP). If it’s disabled you have to enable it, once it’s enabled you are good to go. If yours is enabled you will see a display similar to the image below. To see if the GD library is enabled in your local server, go to your PHP index file and echo **phpinfo();** then you’ll see the GD support in your interface. little example, from (me) Rabbi Emmykolic Step 2:
You will go to your **index.php** and create an image tag. And in the src of the image tag, you’ll write the address of the PHP file where you want to write the GD codes. So the image tag will look like this. An Example From (me) Rabbi Emmykolic Now, this is where you’ll write the PHP code. little example, from (me) Rabbi Emmykolic

After this step, you’ll start writing some functions of the GD library. In the PHP file your GD will start working automatically.

Using GD Library in your projects

Example *****1:* Using GD Library to create a Color-box with a JPEG extension, when saved. *****Step1:* Create an image with the specified dimensions

Step2: Create a color (this first call to imageColorAllocate also automatically sets the image background color)

 $colorRed = imageColorAllocate($image, 255,0,0); 
$colorYellow = imageColorAllocate($image, 255,255,0); 
imageFilledRectangle($image, 50, 50, 250, 150, $colorYellow); 
header("Content-type: image/jpeg"); imageJpeg($image); 

little example, from (me) Rabbi Emmykolic

By running the above code, you will get the output seen in the image below: Example *****2:* How to use GD library to create and rotate a png image. Run the code below to see how to rotate an image. You’ll have to put an image to the PHP file you’re working with, else it won’t dispaly on your interface.

// Create an image with the specified dimensions $image = imagecreatefrompng("africa_coin.png");//and the name of the image with specified extension. // Create a color $colorYellow = imageColorAllocate($image, 255,255,0); // Rotate $image=imagerotate($image, 60, $colorYellow); // Set type of image and send the output header("Content-type: image/png"); imagePng($image); // Release memory imageDestroy($image); 

little example, from (me) Rabbi Emmykolic

By running the above code, you will get the output below:

Why you should use GD Library

GD is an advanced PHP, you can agree with me often advanced PHP developers are the one using GD library. So if you want to be a king in the PHP realm you have to use stuff like this. Another reason you should use GD library is that it helps you do dynamic things with images, in your PHP files. Lastly, It saves you the stress of writing lots of JavaScript, CSS & HTML code…

Other things GD Library can be used for

  • You can use the GD library to build a Captcha system.
  • You can use the GD library to reduce the quality of an image. ## How to generate an image with GD Library

The way to generate images in GD is pretty simple if you have used it before. The first step to making an image to show is to use the **ImageCreate()** function. Then specify the width and height. But if you want to create an image with a png extension you’ll have to use the **ImageCreatePng()** function.

The functions mentioned above, are few listed function that can be used to create a GD library. so the pics below shows some of those function.

little example, from (me) Rabbi Emmykolic

Conclusion

We’ve come to the end of this tutorial, hopefully you got some ideas from the teaching. From the tutorial, we were able to bring to generate an png and jpg images using the GD library.

This is not the end of the tutorial, we’ll talk more about how to use GD to make other things.

About the Author

Emmanuel C. Okolie kick-started his journey as a software engineer in 2020. Over the years, he has grown full-blown skills in JavaScript, PHP, HTML & CSS, and more.

He is freelancing, building clients’ websites, and writing technical tutorials teaching others how to do what he does.

Emmanuel C. Okolie is open and available to hear from you. You can reach him on Linked In, Google, Facebook, GitHub, Twitter, or on his website.

Источник

Оцените статью