Skip to content

Instantly share code, notes, and snippets.

@codee
Last active January 24, 2025 13:23
Show Gist options
  • Save codee/3927343 to your computer and use it in GitHub Desktop.
Save codee/3927343 to your computer and use it in GitHub Desktop.
CodeIgniter: Automatic image rotation library
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
/**
* @file application/libraries/Image_autorotate.php
*/
class Image_autorotate
{
function __construct($params = NULL) {
if (!is_array($params) || empty($params)) return FALSE;
$filepath = $params['filepath'];
$exif = @exif_read_data($filepath);
if (empty($exif['Orientation'])) return FALSE;
$CI =& get_instance();
$CI->load->library('image_lib');
$config['image_library'] = 'gd2';
$config['source_image'] = $filepath;
$oris = array();
switch($exif['Orientation'])
{
case 1: // no need to perform any changes
break;
case 2: // horizontal flip
$oris[] = 'hor';
break;
case 3: // 180 rotate left
$oris[] = '180';
break;
case 4: // vertical flip
$oris[] = 'ver';
break;
case 5: // vertical flip + 90 rotate right
$oris[] = 'ver';
$oris[] = '270';
break;
case 6: // 90 rotate right
$oris[] = '270';
break;
case 7: // horizontal flip + 90 rotate right
$oris[] = 'hor';
$oris[] = '270';
break;
case 8: // 90 rotate left
$oris[] = '90';
break;
default: break;
}
foreach ($oris as $ori) {
$config['rotation_angle'] = $ori;
$CI->image_lib->initialize($config);
$CI->image_lib->rotate();
}
}
}
// END class Image_autorotate
/* End of file Image_autorotate.php */
/* Location: ./application/libraries/Image_autorotate.php */
@codee
Copy link
Author

codee commented Oct 21, 2012

Usage example:

$imageinfo = $this->upload->data();
$full_path = $imageinfo['full_path'];

// check EXIF and autorotate if needed
$this->load->library('image_autorotate', array('filepath' => $full_path));

@boazin
Copy link

boazin commented Apr 5, 2015

Hey @codee. Sorry to wake the deamons 2 years later - but your solution seems really good.
How can you "retake" 'image_width' and 'image_height'? (I need to return them in the response)

@sand3r-2008
Copy link

I was having a problem with your library, to fix it I added at the end of the foreach this line:

$CI->image_lib->clear();

@drusnac19
Copy link

Thank you. It worked for me.

Copy link

ghost commented Jun 3, 2018

Thank you, it's working 100%

@BrainFeeder
Copy link

Perfect! Just what I needed. Had to add @sand3r-2008 his fix though.

@khyatiraval13
Copy link

hello this is not work me for png file pls help me to resolve it

@Andrewsuares
Copy link

Hello, does this save the changes to the original image?

@mustafakucuk
Copy link

It's worked.

@bolivarbutzke
Copy link

Solução para o problema CodeIgniter image rotate! Thanks!!

@turbopixel
Copy link

Thank you! In Codeigniter4 the images were saved incorrectly when uploaded directly from an iPhone.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment