With the help of the GD library, it is possible to create a JPG, GIF, PNG, and other image formats (Formats supported by GD) in PHP. Either output the generated image on a browser or to a file.
Requirements:
- PHP ^7.2.0
- PHP GD Library
The first attempt is to create a JPG image and output it directly on a browser using the img
tag.
Step 1.
Create a PHP file and save it as image.php. This file will be the one to generate the image.
<?php
//set the desired width and height
$width = 400;
$height = 300;
//create a new palette based image
$newImg = imagecreate($width, $height);
//set the image background color to red
$bgColor = imagecolorallocate($newImg, 255, 0, 0);
//set the header content type
header("Content-Type: image/jpeg");
//output the image
imagejpeg($newImg);
//destroy the image
imagedestroy($newImg);
Step 2.
Create an HTML file and save it as image.html. This file will be the place where the image will be displayed.
<!DOCTYPE html>
<html lang="en">
<head>
<title>
Create an image with PHP -
</title>
</head>
<body>
<!-- generate and load the image -->
<img src="image.php">
</body>
</html>
Test.
Open the file image.html on a browser.
Result.
Another Example.
Create a GIF image and save it as myImage.gif.
Step 1.
Create a PHP file and save it as save-image.php. This file will save the generated image.
<?php
//set the desired width and height
$width = 200;
$height = 300;
//create a new palette based image
$newImg = imagecreate($width, $height);
//set the image background color to blue
$bgColor = imagecolorallocate($newImg, 0, 0, 255);
//save the image
imagegif($newImg,"myImage.gif");
//destroy the image
imagedestroy($newImg);
Test.
Open the file save-image.php on a browser or in the command line.
And then check the folder where the file save-image.php is located, a new image file named myImage.gif should now exist there.
Result.
The file image myImage.gif should look like below.
To save the image inside a folder named images.
- Change this.
//save the image imagegif($newImg,"myImage.gif");
- To this.
//save the image imagegif($newImg,"images/myImage.gif");
Notice that the name of the folder (images) was added before the name of the image (myImage.gif).
Notes:
Differences between outputting the image to a browser and saving it to a file.
- The header
Content-Type
is not needed when saving the image to a file.//this line is not needed when saving the image to a file header("Content-Type: image/gif");
- When saving the image to a file, a second parameter is required upon creating the image (
imagegif()
for example), where it has the name and the path where to save the file.//myImage.gif is required if the image should be saved imagegif($newImg,"myImage.gif");
Leave a Reply