图片exif属性导致html中图片被转了90度

2020-12-07

拍摄图片时由于不同的拍摄角度的可能会引起一个问题:图片在html页面显示时被旋转了90度;这是由于图片exif信息中的Orientation被赋予了图片的拍摄方向,我们可以在上传图片时将其修改

<?php
/** 需要开启php_mbstring.dll和php_exif.dll扩展
 * @param file string 文件绝对路径
 * @return {*}
 */
function deal_img_exif($file)
{
    $exif = exif_read_data($file);
	if ($exif) {
		if (in_array($exif['Orientation'],[3,6,8])) {
			$image = imagecreatefromstring(file_get_contents($file));
			switch($exif['Orientation']) {
				case 8:
					$image = imagerotate($image,90,0);
					break;
				case 3:
					$image = imagerotate($image,180,0);
					break;
				case 6:
					$image = imagerotate($image,-90,0);
					break;
			}
			$ext = image_type_to_mime_type(exif_imagetype($file));
			switch($ext) {
				case 'image/gif':
					unlink($file);
					imagegif($image,$file);
					break;
				case 'image/jpeg':
					unlink($file);
					imagejpeg($image,$file);
					break;
				case 'image/png':
					unlink($file);
					imagepng($image,$file);
					break;
				case 'image/bmp':
					unlink($file);
					imagebmp($image,$file);
					break;
			}
		}
	}
}
{/if}