Para detectar la orientación de una foto sacada con tu cámara digital deberemos obtener la información Exif (Exchangeable image file format) de la foto. Esta información está presente en los formatos JPEG y TIFF generados por la mayoría de las cámaras digitales.
Con PHP esto es muy sencillo si tenemos instalada la extensión Exif. Lo que tenemos que hacer es detectar la información de la orientación de la imagen y rotarla usando la librería GD.
Vamos a ver un ejemplo de como hacerlo:
class Photo { private static function mirrorImage ( $imgsrc ) { $width = imagesx ( $imgsrc ); $height = imagesy ( $imgsrc ); $src_x = $width -1; $src_y = 0; $src_width = -$width; $src_height = $height; $imgdest = imagecreatetruecolor ( $width, $height ); if ( imagecopyresampled ( $imgdest, $imgsrc, 0, 0, $src_x, $src_y, $width, $height, $src_width, $src_height ) ) { return $imgdest; } return $imgsrc; } public static function adjustPhotoOrientation($full_filename) { $exif = exif_read_data($full_filename); if($exif && isset($exif['Orientation'])) { $orientation = $exif['Orientation']; if($orientation != 1){ $img = imagecreatefromjpeg($full_filename); $mirror = false; $deg = 0; switch ($orientation) { case 2: $mirror = true; break; case 3: $deg = 180; break; case 4: $deg = 180; $mirror = true; break; case 5: $deg = 270; $mirror = true; break; case 6: $deg = 270; break; case 7: $deg = 90; $mirror = true; break; case 8: $deg = 90; break; } if ($deg) $img = imagerotate($img, $deg, 0); if ($mirror) $img = self::mirrorImage($img); imagejpeg($img, $full_filename); } } return true; } }
Ahora solo tenemos que hacer Photo::adjustPhotoOrientation($ruta_absoluta_de_la_imagen) y ya tenemos la foto rotada correctamente.
Comentarios