With the help of the GD library, it is possible to create a JPG, GIF, or PNG image in PHP. Either output the generated image to a browser or to a file.
For example.
Create a JPG image and output it directly on the browser on an img
tag.
Create two files, one PHP file which will generate the image, and one HTML file that will display the generated image.
/*
* save this as 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);
<!DOCTYPE html>
<html lang="en">
<head>
<title>Create an image with PHP - ConsistentCoder.com</title>
</head>
<body>
<!--
* save this as image.html
-->
<!-- generate and load the image -->
<img src="image.php">
</body>
</html>
Once the file image.html is opened, the result will be like the one below.
Other Example
Create a GIF image and save it as myImage.gif.
//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);
Result.
To save the image inside a folder or directory named images.
//save the image
imagegif($newImg,"myImage.gif");
//save the image
imagegif($newImg,"images/myImage.gif");
Notes:
Differences between outputting the image to a browser and saving it to a file.
//this line is not needed when saving the image to a file
header("Content-Type: image/gif");
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");
Create a NodeJs Hello World example - https://t.co/7PS2IOu7bF
— Consistent Coder (@ConsistentCoder) Nobyembre 17, 2015