这里需要开启PHP的这两个扩展(默认是关闭的) php_mbstring.dll php_exif.dll
否则会报 call an undefined function exif_imagetype() 类似的错误
可能出现的问题:
exif_read_data(4430fd973e0a01392333296720ed1f29.jpg): Illegal IFD size
这是PHP版本的问题,我测试了php5.6.27, 7.0.12, 7.1.13 都出这个报错提示,属于官方的BUG;
解决办法: 升级到7.2或以上吧!!!
<?php /** * barry * 图像处理 */ class ImageDispose { private $mFilePath; private $mSavePath; private $mRotateDegrees; private $errormsg; public function setFilePath($value) { $this->mFilePath = $value; $this->mSavePath = $value; return $this; } public function setSavePath($value) { is_dir(dirname($value)) or mkdir(dirname($value), 0755, true); $this->mSavePath = $value; return $this; } public function setRotateDegrees($value) { $this->mRotateDegrees = (int)$value; return $this; } public function saveRotateResult() { $this->mImageType = exif_imagetype($this->mFilePath); if (false === $this->mImageType) { throw new \Exception('文件已损坏!', 1); } $this->IsNeedRotate = $this->checkIsNeedRotate(); if (false === $this->IsNeedRotate) { return true; } switch ($this->mImageType) { case IMAGETYPE_GIF: $source = imagecreatefromgif($this->mFilePath); break; case IMAGETYPE_JPEG: $source = imagecreatefromjpeg($this->mFilePath); break; case IMAGETYPE_PNG: $source = imagecreatefrompng($this->mFilePath); break; case IMAGETYPE_WBMP: $source = imagecreatefromwbmp($this->mFilePath); break; case IMAGETYPE_WEBP: $source = imagecreatefromwebp($this->mFilePath); break; default: throw new \Exception('不支持的文件类型', 1); break; } $rotate = imagerotate($source, $this->mRotateDegrees, 0); $result = imagejpeg($rotate, $this->mSavePath); imagedestroy($source); return $result; } public function checkIsNeedRotate() { $exif = exif_read_data($this->mFilePath); //部分Android拍照的 Orientation 属性都是1,判断不出是否需要旋转了 if (isset($exif['Orientation']) && $exif['Orientation'] > 1) { $this->IsNeedRotate = true; switch($exif['Orientation']) { case 8: $this->mRotateDegrees = 90; break; case 3: $this->mRotateDegrees = 180; break; case 6: $this->mRotateDegrees = -90; break; } } else { $this->IsNeedRotate = false; } return $this->IsNeedRotate; } /** * 返回错误信息 * @access public * @return string|array */ public function getErrorMsg() { return $this->errormsg; } }
转载请注明本文标题和链接:《 PHP通过Orientation判断图像是否需要旋转 》
网友评论 0