/**
* 自动纠正图片方向
* 方向经过旋转的图片,在电脑、手机、浏览器中查看时一般会自动纠正,
* 但是在生成缩略图、使用某些打印控件打印时,可能会出现方向不正确的情况。
*/
function rotateImage($imagePath) {
if (!function_exists('exif_read_data')) {
return false; // EXIF扩展未启用
}
if (!file_exists($imagePath)) {
return false; // 文件不存在
}
$exif = exif_read_data($imagePath);
$orientation=1;
if ($exif && isset($exif['Orientation'])) {
$orientation= (int)$exif['Orientation'];
}
// 读取图片
$size = getimagesize($imagePath);
$width = $size[0];
$height= $size[1];
$mime = $size['mime'];
switch ($mime) {
case 'image/jpeg':
$image = imagecreatefromjpeg($imagePath);
break;
case 'image/png':
$image = imagecreatefrompng($imagePath);
break;
case 'image/gif':
$image = imagecreatefromgif($imagePath);
break;
default:
header('Content-Type: '.$mime);
echo file_get_contents($imagePath);
return false;
}
// 根据方向值进行旋转
switch ($orientation) {
case 2:
// 水平翻转
imageflip($image, IMG_FLIP_HORIZONTAL);
break;
case 3:
// 旋转180°
$image = imagerotate($image, 180, 0);
break;
case 4:
// 垂直翻转
imageflip($image, IMG_FLIP_VERTICAL);
break;
case 5:
// 顺时针90° + 水平翻转
$image = imagerotate($image, -90, 0);
imageflip($image, IMG_FLIP_HORIZONTAL);
break;
case 6:
// 顺时针90°
$image = imagerotate($image, -90, 0);
break;
case 7:
// 逆时针90° + 水平翻转
$image = imagerotate($image, 90, 0);
imageflip($image, IMG_FLIP_HORIZONTAL);
break;
case 8:
// 逆时针90°
$image = imagerotate($image, 90, 0);
break;
}
// 输出图片
switch ($mime) {
case 'image/jpeg':
header('Content-Type: image/jpeg');
imagejpeg($image, null, 90); // 90% 质量
break;
case 'image/png':
header('Content-Type: image/png');
imagepng($image, null, 9); // 9级压缩
break;
case 'image/gif':
header('Content-Type: image/gif');
imagegif($image);
break;
}
imagedestroy($image);
}
/*获取图片方向*/
function getImageOrientation($imagePath) {
if (!function_exists('exif_read_data')) {
return return_data(1, 'EXIF扩展未启用');
}
if (!file_exists($imagePath)) {
return return_data(2, '文件不存在');
}
$exif = @exif_read_data($imagePath);
if($exif===null)return return_data(2,'方向无法读取:'.$imagePath);
$orientation=0;
if ($exif && isset($exif['Orientation'])) {
$orientation= (int)$exif['Orientation'];
}
// 方向值说明:
// 1 = 正常
// 2 = 水平翻转
// 3 = 旋转180°
// 4 = 垂直翻转
// 5 = 顺时针90°+水平翻转
// 6 = 顺时针90°
// 7 = 逆时针90°+水平翻转
// 8 = 逆时针90°
$txt='';
switch ($orientation) {
case 1:
$txt="正常方向 (0°)";
break;
case 2:
$txt="水平翻转";
break;
case 3:
$txt="旋转 180°";
break;
case 4:
$txt="垂直翻转";
break;
case 5:
$txt="顺时针 90° + 水平翻转";
break;
case 6:
$txt="顺时针 90°";
break;
case 7:
$txt="逆时针 90° + 水平翻转";
break;
case 8:
$txt="逆时针 90°";
break;
default:
$txt="未知方向";
break;
}
return return_data(0, $orientation.chr(32).$txt, array('orientation'=>$orientation, 'description'=>$txt));
}
function return_data($code=0,$msg='',$data=array()){
return array('code'=>$code, 'msg'=>$msg, 'data'=>$data);
}