private static Document GetOrientedDocument(byte[] bytes, out ExifValueCollection exifMetadata) { exifMetadata = null; Document doc = null; // Load the image into a Bitmap so the EXIF orientation transform can be applied. using (Bitmap image = WebPFile.Load(bytes)) { byte[] exifBytes = WebPFile.GetExifBytes(bytes); if (exifBytes != null) { exifMetadata = ExifParser.Parse(exifBytes); if (exifMetadata.Count > 0) { MetadataEntry orientationProperty = exifMetadata.GetAndRemoveValue(MetadataKeys.Image.Orientation); if (orientationProperty != null) { RotateFlipType transform = MetadataHelpers.GetOrientationTransform(orientationProperty); if (transform != RotateFlipType.RotateNoneFlipNone) { image.RotateFlip(transform); } } MetadataEntry xResProperty = exifMetadata.GetAndRemoveValue(MetadataKeys.Image.XResolution); MetadataEntry yResProperty = exifMetadata.GetAndRemoveValue(MetadataKeys.Image.YResolution); MetadataEntry resUnitProperty = exifMetadata.GetAndRemoveValue(MetadataKeys.Image.ResolutionUnit); if (xResProperty != null && yResProperty != null && resUnitProperty != null) { if (MetadataHelpers.TryDecodeRational(xResProperty, out double xRes) && MetadataHelpers.TryDecodeRational(yResProperty, out double yRes) && MetadataHelpers.TryDecodeShort(resUnitProperty, out ushort resUnit)) { if (xRes > 0.0 && yRes > 0.0) { double dpiX, dpiY; switch ((MeasurementUnit)resUnit) { case MeasurementUnit.Centimeter: dpiX = Document.DotsPerCmToDotsPerInch(xRes); dpiY = Document.DotsPerCmToDotsPerInch(yRes); break; case MeasurementUnit.Inch: dpiX = xRes; dpiY = yRes; break; default: // Unknown ResolutionUnit value. dpiX = 0.0; dpiY = 0.0; break; } if (dpiX > 0.0 && dpiY > 0.0) { try { image.SetResolution((float)dpiX, (float)dpiY); } catch { // Ignore any errors when setting the resolution. } } } } } } } doc = Document.FromGdipImage(image); } return(doc); }