PHP imagejpeg() Function Tutorial 🎯

beginner
23 min

PHP imagejpeg() Function Tutorial 🎯

Welcome to this comprehensive guide on using the imagejpeg() function in PHP! This function is a powerful tool for saving an image in the JPEG format. By the end of this lesson, you'll be able to create, manipulate, and save images using PHP.

Let's dive right in! πŸ’‘

Understanding the imagejpeg() Function πŸ“

The imagejpeg() function is used to save an image as a JPEG file. It writes the contents of an image to a file or to output.

php
imagejpeg($image, $filename, $quality);
  • $image: The image resource to be saved as a JPEG file.
  • $filename: The name of the file to which the image will be saved.
  • $quality: The quality of the JPEG image (a value between 0 and 100).

πŸ’‘ Pro Tip: The imagejpeg() function works with images created using other PHP functions like imagecreate(), imagecreatefromjpeg(), and so on.

Creating an Image 🎨

First, let's create a simple image using PHP. We'll use the imagecreate() function to create a blank image.

php
$image = imagecreate(200, 200);

In this example, we're creating an image that's 200 pixels wide and 200 pixels tall.

Filling the Image 🎨

Now that we have our blank image, let's fill it with a color.

php
$color = imagecolorallocate($image, 255, 255, 255); imagefilledrectangle($image, 0, 0, 200, 200, $color);

Here, we're allocating white color and filling the entire image with it using imagefilledrectangle().

Saving the Image πŸ’Ύ

Finally, let's save our image using the imagejpeg() function.

php
header('Content-Type: image/jpeg'); imagejpeg($image); imagedestroy($image);

In this example, we're setting the content type to image/jpeg, sending the image to the browser, and destroying the image resource.

Quick Quiz
Question 1 of 1

What does the `imagejpeg()` function do in PHP?

Advanced Example: Adding Text to an Image πŸ“

Let's take it a step further and add some text to our image.

php
$font = 'arial.ttf'; $text = 'Hello, World!'; $font_size = 15; $color = imagecolorallocate($image, 0, 0, 0); imagettftext($image, $font_size, 0, 20, 50, $color, $font, $text);

In this example, we're adding the text "Hello, World!" to our image using the imagettftext() function.

Quick Quiz
Question 1 of 1

Which PHP function is used to add text to an image?

That's it for today! With this lesson, you're well on your way to mastering the imagejpeg() function in PHP. Keep practicing and experimenting, and don't forget to come back for more tutorials at CodeYourCraft. πŸ’‘ Happy coding! πŸš€