PHP Creating an image


Example

To create a blank image, use the imagecreatetruecolor function:

$img = imagecreatetruecolor($width, $height);

$img is now a resource variable for an image resource with $widthx$height pixels. Note that width counts from left to right, and height counts from top to bottom.

Image resources can also be created from image creation functions, such as:

  • imagecreatefrompng
  • imagecreatefromjpeg
  • other imagecreatefrom* functions.

Image resources may be freed later when there are no more references to them. However, to free the memory immediately (this may be important if you are processing many large images), using imagedestroy() on an image when it is no longer used might be a good practice.

imagedestroy($image);

Converting an image

Images created by image conversion does not modify the image until you output it. Therefore, an image converter can be as simple as three lines of code:

function convertJpegToPng(string $filename, string $outputFile) {
    $im = imagecreatefromjpeg($filename);
    imagepng($im, $outputFile);
    imagedestroy($im);
}