imagesx() function in PHP

The imagesx() function gets the width of an image resource in PHP. It returns the width of the image in pixels or FALSE on errors.

Syntax

imagesx(image)

Parameters

  • image − An image resource created by one of the image creation functions like imagecreatetruecolor(), imagecreatefromjpeg(), etc.

Return Value

The imagesx() function returns the width of the image in pixels as an integer, or FALSE on failure.

Example

The following example demonstrates how to get the width of a newly created image resource ?

<?php
    $img = imagecreatetruecolor(450, 250);
    echo "Width of the image: " . imagesx($img) . " pixels";
?>
Width of the image: 450 pixels

Practical Example

Here's how you can use imagesx() to get dimensions of an image before processing ?

<?php
    // Create a sample image
    $width = 300;
    $height = 200;
    $image = imagecreatetruecolor($width, $height);
    
    // Get the width using imagesx()
    $imageWidth = imagesx($image);
    $imageHeight = imagesy($image);
    
    echo "Original dimensions: {$imageWidth} x {$imageHeight}
"; echo "Aspect ratio: " . round($imageWidth / $imageHeight, 2); // Clean up memory imagedestroy($image); ?>
Original dimensions: 300 x 200
Aspect ratio: 1.5

Conclusion

The imagesx() function is essential for getting image width in PHP image processing. Use it alongside imagesy() to get complete dimension information before manipulating images.

Updated on: 2026-03-15T07:48:33+05:30

318 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements