What are some common pitfalls when working with image dimensions in PHP?
One common pitfall when working with image dimensions in PHP is not properly handling image orientation. Images can have different orientations (landscape, portrait, square) which can affect how their dimensions are interpreted. To solve this, you can use functions like `getimagesize()` or `exif_read_data()` to get the image dimensions and adjust them accordingly based on the orientation.
// Get image dimensions with correct orientation
function getImageDimensions($imagePath) {
$imageSize = getimagesize($imagePath);
if (isset($imageSize['mime']) && strpos($imageSize['mime'], 'image/') === 0) {
$orientation = 1;
if (function_exists('exif_read_data')) {
$exif = exif_read_data($imagePath);
$orientation = $exif['Orientation'] ?? 1;
}
if ($orientation >= 5) {
$temp = $imageSize[0];
$imageSize[0] = $imageSize[1];
$imageSize[1] = $temp;
}
return $imageSize;
}
return false;
}
// Example usage
$imagePath = 'path/to/image.jpg';
$imageDimensions = getImageDimensions($imagePath);
if ($imageDimensions) {
echo 'Width: ' . $imageDimensions[0] . 'px, Height: ' . $imageDimensions[1] . 'px';
} else {
echo 'Failed to get image dimensions.';
}