9951 explained code solutions for 126 technologies

php-gdHow to auto orient image

We can use EXIF data to get image orientation (in case it has this data set):


$file = 'source.jpg';
$im = imagecreatefromjpeg($file);

$rotation = [0, 0, 0, 180, 0, 0, -90, 0, 90][@exif_read_data($file)['COMPUTED']['Orientation'] ?: 0];
if ( $rotation ) {
  $im = imagerotate($im, $rotation, 0);

imagejpeg($im, 'result.jpg');ctrl + c

source image file to auto orient


creates GD image object from given PNG image


returns EXIF data of a specified image


define rotation angle accordingly to image orientation


rotates $im image by $rotation


save given image to the given JPEG file