图像读取Exif小知识,图像扶正,还原拍摄时的角度

在作人脸识别的时候发现不少手机拍摄的图像在C#读取以后方向出现了错误,Bitmap中的宽度和实际的windows的文件属性内的参数相反,引发一阵测试和思考,后来百度出来能够用Exif来解决git

github有相关Exif介绍github

https://github.com/dlemstra/Magick.NET/blob/784e23b1f5c824fc03d4b95d3387b3efe1ed510b/Magick.NET/Core/Profiles/Exif/ExifTag.cswindows

维基百科也有说明测试

https://en.wikipedia.org/wiki/Exifspa

实际代码是3d

/// <summary>
        /// 根据图片exif调整方向
        /// </summary>
        /// <param name="sm"></param>
        /// <returns></returns>
        public static Bitmap RotateImage(Stream sm)
        {
            Image img = Image.FromStream(sm);
            var exif = img.PropertyItems;
            byte orien = 0;
            var item = exif.Where(m => m.Id == 274).ToArray();
            if (item.Length > 0)
                orien = item[0].Value[0];
            switch (orien)
            {
                case 2:
                    img.RotateFlip(RotateFlipType.RotateNoneFlipX);//horizontal flip
                    break;
                case 3:
                    img.RotateFlip(RotateFlipType.Rotate180FlipNone);//right-top
                    break;
                case 4:
                    img.RotateFlip(RotateFlipType.RotateNoneFlipY);//vertical flip
                    break;
                case 5:
                    img.RotateFlip(RotateFlipType.Rotate90FlipX);
                    break;
                case 6:
                    img.RotateFlip(RotateFlipType.Rotate90FlipNone);//right-top
                    break;
                case 7:
                    img.RotateFlip(RotateFlipType.Rotate270FlipX);
                    break;
                case 8:
                    img.RotateFlip(RotateFlipType.Rotate270FlipNone);//left-bottom
                    break;
                default:
                    break;
            }
            return (Bitmap)img;
        }
相关文章
相关标签/搜索