Skip to content
Tutorials Center
My learning

Topics

Lesson 71 of 147 ยท Working with Files

Working with Images: GD

Create, inspect, resize, crop and watermark images in PHP with the GD extension, keep transparency, and save JPEG, PNG, WebP or AVIF at the right quality.

Almost every website handles pictures: profile avatars, product photos, blog headers, screenshots attached to support tickets. The files people upload are rarely the right size. A phone photo is 4,000 pixels wide and 5 MB, while the avatar slot on your page is 96 pixels. Sending the original wastes bandwidth and makes pages slow, so the server's job is to turn each upload into a few well-sized, well-compressed copies.

PHP's built-in tool for this is the GD extension. It can create images from scratch, load JPEG, PNG, GIF, WebP, AVIF and BMP files, draw shapes and text, resize, crop and rotate, and save the result in any of those formats. GD is bundled with PHP and enabled on almost every host, and it's available in our editor too. (The other common choice, the Imagick extension built on ImageMagick, supports more formats and effects, but it's a separate install and isn't available here.)

This lesson builds on Reading and Writing Files and pairs naturally with File Uploads, which explains how uploaded files reach your script.

Our editor shows text, not pictures. To let you see what the code does, several examples include a small preview() helper that shrinks the image and prints it as characters: dark pixels become @ and %, light pixels become . and spaces. On a real server you'd save the file or send it to the browser instead.

Images are GdImage objects

You start with a canvas. imagecreatetruecolor($width, $height) creates a black image with full 24-bit color plus an alpha (transparency) channel. Since PHP 8.0, GD functions return a GdImage object rather than an old-style resource, and PHP frees its memory automatically when the variable goes out of scope.

Colors are plain integers. imagecolorallocate($image, $red, $green, $blue) builds one from three values from 0 to 255, and imagecolorallocatealpha() adds a fourth value for transparency. GD's alpha runs backwards compared with CSS: 0 is fully opaque and 127 is fully transparent.

Coordinates start at the top-left corner, (0, 0), with x growing to the right and y growing downward. Then you draw: imagefill() floods an area, imagerectangle() and imagefilledrectangle() draw boxes, imagefilledellipse() takes a center point plus a width and height, imageline() draws lines, and imagestring() writes text in one of five built-in bitmap fonts.

PHP Drawing an image from scratch

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The preview shows the frame, the circle, the dark bar and the thin line. The text is there too, but at this size it shrinks to a couple of characters. imagepng($image, 'badge.png') saved a real 1,351-byte PNG file in the editor's working folder, and getimagesize() read its size back.

The preview() helper itself is a nice tour of pixel access. imagescale() shrinks the image, imagecolorat() returns each pixel as an integer, and the bit shifts take out the red, green and blue parts ($rgb >> 16 & 0xFF is red). The weights 0.299, 0.587 and 0.114 turn color into perceived brightness, because human eyes are most sensitive to green.

imagestring() uses tiny built-in pixel fonts with ASCII characters only. For real typography, use imagettftext($image, $size, $angle, $x, $y, $color, $fontFile, $text) with a TrueType or OpenType font file that you ship with your app. It supports any size, rotation and UTF-8 text. Our sandbox has no font files, so the examples here stick to the built-in fonts.

Inspecting images with getimagesize()

Before you load an image, ask what it is. getimagesize($file) reads just the file's header and returns an array: index 0 is the width, 1 the height, 2 an IMAGETYPE_* constant, 3 a ready-made width="โ€ฆ" height="โ€ฆ" string for HTML, and 'mime' the MIME type. For anything that isn't an image it returns false. getimagesizefromstring() does the same for bytes already in memory.

The important part is that getimagesize() looks at the contents, not the file name:

PHP Inspecting files with getimagesize

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

holiday.png is reported as image/jpeg because that's what its bytes are, and avatar.jpg is correctly rejected even though its name says JPEG. image_type_to_extension() suggests the right extension for each real type (.jpeg for JPEG; many sites prefer .jpg, which is just as valid).

To load an image, use the function for its format (imagecreatefromjpeg(), imagecreatefrompng(), imagecreatefromwebp(), imagecreatefromgif(), imagecreatefromavif()), or imagecreatefromstring($bytes), which detects the format itself. All of them return false and print a warning for data they can't decode, so check the type with getimagesize() first.

Images need much more memory than their file size

A JPEG is compressed; a GdImage is not. GD stores about 4 bytes per pixel, so a 6,000 ร— 4,000 photo (24 megapixels) that's 6 MB on disk needs roughly 96 MB of memory once loaded, and every resized copy adds more. That's why you check the dimensions from getimagesize() before decoding: a tiny, highly compressed file can declare enormous dimensions (a "decompression bomb") and exhaust your memory_limit. Reject anything above a pixel limit that suits your site.

Resizing and keeping the aspect ratio

The aspect ratio is width divided by height. Squash a 4:3 photo into a 1:1 box and faces get stretched, so resizing almost always means "make it as large as possible while fitting inside a box". The scale factor is the smaller of the two ratios maxWidth / width and maxHeight / height. Capping it at 1.0 stops small images from being enlarged, which would only make them blurry.

GD has two copy functions that resize as they copy:

  • imagecopyresampled() blends all the source pixels that fall into each target pixel. It's slower and looks right. Use it.
  • imagecopyresized() simply picks one source pixel per target pixel. It's fast, but fine detail turns into jagged edges, or disappears completely.

Both take the same ten arguments: target and source image, the target's x and y, the source's x and y, then the target width and height and the source width and height. Since the source rectangle is a parameter, you can copy just part of an image, which is how cropping works below.

PHP Resizing while keeping the aspect ratio

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Every box result keeps its shape: the landscape photo becomes 800 ร— 600, the portrait 600 ร— 800, the 500 ร— 300 image stays as it is, and the very wide banner becomes 800 ร— 53.

The stripe test shows why resampling matters. The source is half black and half white, so from a distance it looks mid-gray. imagecopyresampled() averages each group of pixels and gets 128, the correct gray. imagecopyresized() happens to land on a white stripe every time and produces a pure white image (255), which is completely wrong. Real photos have fine detail like hair, fabric and text, and that's exactly what breaks with the fast version.

For quick jobs, imagescale($image, $width) resizes in one call and calculates the height from the aspect ratio when you leave it out. imagescale($image, $width, $height) forces both, which can distort the image.

Keeping transparency

PNG, WebP, GIF and AVIF can have transparent pixels, and GD loses them unless you ask it not to. Two switches matter on the target image:

  • imagealphablending($target, false) makes GD copy alpha values instead of blending them with the black background of the new canvas.
  • imagesavealpha($target, true) makes imagepng() and imagewebp() write the alpha channel into the file.
PHP Keeping transparency

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Without the two settings, the transparent corner comes back as opaque black (alpha 0), the classic "black box around my logo" bug. With them, the corner stays fully transparent (alpha 127) and the red circle is untouched. JPEG has no transparency at all, so if you convert a transparent PNG to JPEG, fill the canvas with white (or your page's background color) first.

Cropping and square thumbnails

Avatars and product grids usually need exact sizes, such as 150 ร— 150, whatever shape the original is. Fitting inside the box would leave empty bars, so thumbnails use the opposite strategy, often called cover: cut the biggest centered square (or other target shape) out of the image, then scale that piece down. Everything outside the square is cut off.

With imagecopyresampled() this takes a single call, because the source rectangle can be any part of the image:

PHP Square thumbnails with a center crop

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The original is 900 ร— 400, so the largest square is 400 ร— 400, starting at x = 250. The thumbnail keeps the circle and drops the black bars at the sides. If you wanted to keep everything, you'd fit the image inside the square instead and fill the empty space with a background color: that's the contain strategy, the same fitWithin() calculation from the previous section.

imagecrop() cuts a rectangle without scaling and returns a new image (or false if the rectangle is invalid). Its sibling imagecropauto() trims uniform borders, which is handy for scanned documents. A centered crop is a good default; sites that care about faces let the user drag the crop area in the browser and send the chosen x, y and size along with the upload.

Two more transformations come up often: imagerotate($image, $degrees, $backgroundColor) rotates counterclockwise, and imageflip($image, IMG_FLIP_HORIZONTAL) mirrors the image in place.

Photos from phones: EXIF orientation

Phone cameras often store a portrait photo as a landscape image plus an EXIF Orientation tag that says "rotate me 90ยฐ". Browsers obey the tag, but GD ignores it, and re-encoding throws the tag away, so your thumbnail ends up lying on its side. Read the tag with the exif extension and rotate before resizing:

PHP
$exif = @exif_read_data($path);   // false for files without EXIF; the @ hides harmless warnings

$image = match ($exif['Orientation'] ?? 1) {
    3 => imagerotate($image, 180, 0),
    6 => imagerotate($image, -90, 0),   // stored sideways: turn clockwise
    8 => imagerotate($image, 90, 0),
    default => $image,
};

Orientations 2, 4, 5 and 7 add a mirror flip; they're rare outside of front cameras, and imageflip() handles them.

Watermarks

A watermark marks images as yours: a copyright line, a logo, or "PREVIEW" across a stock photo. There are two kinds, and both depend on alpha blending, which must be on (the default for true-color images) while you draw onto the photo:

  • Text: imagestring() (or imagettftext() with a font file), usually on a half-transparent band so it stays readable on light and dark photos. imagefontwidth() and imagefontheight() tell you how big built-in text will be, so you can place it in a corner.
  • A logo: a transparent PNG copied onto the photo with imagecopy(). With blending on, its transparent pixels let the photo show through. To make an opaque logo half see-through, use imagecopymerge($dst, $src, โ€ฆ, $percent) instead.
PHP Watermarking with text and a logo

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

In the preview you can see the ring in the top-left corner, with the photo showing through its transparent middle and corners, and the dark band with the text in the bottom-right corner. Try setting imagealphablending($image, false) in addLogo(): the transparent pixels are then copied as they are, and since JPEG can't store transparency, they turn into a black square in the saved file.

Watermarking happens once, when the image is processed, and the result is saved. Don't watermark on every request; it's slow and wastes CPU. Keep the clean original in private storage in case you want to change the watermark later.

Saving: formats and quality

The saving functions take the image, a target, and a quality setting:

Function Quality argument Best for
imagejpeg($img, $file, 75) 0 to 100 (default about 75) photos
imagepng($img, $file, 6) compression 0 to 9; always lossless logos, screenshots, transparency
imagewebp($img, $file, 80) 0 to 100, or IMG_WEBP_LOSSLESS photos and graphics; smaller than JPEG
imageavif($img, $file, 50, 6) 0 to 100, plus speed 0 (slow, small) to 10 photos; smallest, slowest to encode
imagegif($img, $file) none; 256 colors only legacy, tiny icons

Note the trap with PNG: its third argument is not a quality. Every PNG is lossless; the number only trades CPU time for file size. Passing null instead of a file name writes the image to the output, which you can capture with output buffering:

PHP Comparing output formats and quality

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

For this photo-like image, lossless PNG is the biggest at about 190 KB. JPEG at quality 75 is about a third of that, WebP at quality 80 is smaller still, and AVIF is the smallest. Each image is different, so test with your own pictures, but the ranking is typical: for photos, WebP or AVIF with a JPEG fallback is the modern choice, and all current browsers display both. The last line shows a data URL, an image embedded directly in HTML or CSS. Base64 makes data about a third bigger, so use it only for tiny images.

To send a generated image straight to the browser, set the content type and write to the output. That's how dynamic images like charts, captchas or social-media preview cards are served:

PHP
<?php

header('Content-Type: image/webp');
header('Cache-Control: public, max-age=86400');

imagewebp($image, null, 80);

Generating on every request is expensive, though. For uploads, create the sizes once and serve them as plain files.

Putting it together: processing an upload

Here's the whole workflow as one function, the way you'd use it behind an upload form. It checks the real type and the pixel count before decoding, decodes once, and saves several sizes as WebP under random names. Re-encoding is also a security measure: the saved files contain only pixels that GD drew, so any metadata, hidden script or GPS location in the upload is gone. Our editor has no form, so the "uploads" are bytes made in the script:

PHP A safe pipeline for uploaded images

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The holiday photo becomes three WebP files of 1200, 600 and 150 pixels wide. The 3-megapixel scan is rejected before GD spends 12 MB decoding it, and the PDF is rejected by type. The small image isn't enlarged: its "large" and "medium" copies stay 400 ร— 300. The random part of each name is shortened to โ€ฆ in the output because it changes on every run.

On a real site, $bytes would come from file_get_contents($_FILES['photo']['tmp_name']) after the upload checks from File Uploads, and big images would be processed by a background job rather than while the user waits.

imagedestroy() has done nothing since PHP 8.0, when images became objects that are freed automatically, and PHP 8.5 marks it deprecated. Old tutorials call it after every operation; in modern code, just let the variable go out of scope, or unset() it in a long loop.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. An uploaded file is named cat.jpg and the browser says its type is image/jpeg. What is the reliable way to find out what it really is?

    The file name and the browser's type are both sent by the client and can be anything. getimagesize() reads the real format from the bytes and returns false for non-images.
  2. 2. What size does a 3000 x 2000 image get when you fit it inside an 800 x 800 box while keeping the aspect ratio?

    The scale factor is the smaller of 800/3000 and 800/2000, which is 0.2667. 3000 times that is 800 and 2000 times that is 533.
  3. 3. You resize a transparent PNG logo and the transparent areas turn black. What did you forget on the new canvas?

    A new true-color canvas is black. Without these two settings GD blends the transparent pixels onto that black background and doesn't save the alpha channel.
  4. 4. What does the third argument mean in imagepng($image, 'logo.png', 9)?

    PNG is always lossless. Its level from 0 to 9 only trades encoding time for file size. JPEG, WebP and AVIF take a real quality value.
  5. 5. Why should you check the dimensions from getimagesize() before calling imagecreatefromstring()?

    Compressed files can declare enormous dimensions. Checking the pixel count first lets you reject them before decoding exhausts the memory limit.

Summary

  • GD creates and loads images as GdImage objects; colors come from imagecolorallocate()/imagecolorallocatealpha() (alpha 0 is opaque, 127 transparent), and (0, 0) is the top-left corner.
  • getimagesize() and getimagesizefromstring() read the real type and size from the header; check type and pixel count before decoding, since each pixel takes about 4 bytes of memory.
  • Fit images inside a box with scale = min(maxW / w, maxH / h, 1), and resize with imagecopyresampled() (or imagescale()), never imagecopyresized() for photos.
  • Keep transparency with imagealphablending($target, false) and imagesavealpha($target, true).
  • Make exact-size thumbnails by cropping the centered square (cover) in the source rectangle of imagecopyresampled(); imagecrop(), imagerotate() and imageflip() do the rest, and EXIF orientation fixes sideways phone photos.
  • Watermark with blending on: text on a half-transparent band, or a transparent PNG logo via imagecopy().
  • Save photos as WebP or AVIF (with JPEG as a fallback), graphics as PNG; process uploads once into several sizes and re-encode them to strip anything hidden. imagedestroy() is deprecated in PHP 8.5.

Next: PHP and HTML Templates