public static BitmapImage BitmapFromStream(Stream stream, BitmapLoadProperties loadProperties = null) { try { var properties = Images.GetImageProperties(stream); var aspect = new AspectRatio(properties.Width, properties.Height); stream.Seek(0, SeekOrigin.Begin); var bitmap = new BitmapImage(); bitmap.BeginInit(); if (loadProperties?.MaxDecodePixelWidth > 0 && properties?.Width > loadProperties?.MaxDecodePixelWidth) { if (loadProperties.DpiScale != null) { bitmap.DecodePixelWidth = (int)Math.Round(loadProperties.MaxDecodePixelWidth * loadProperties.DpiScale.Value.DpiScaleX); } else { bitmap.DecodePixelWidth = loadProperties.MaxDecodePixelWidth; } } if (loadProperties?.MaxDecodePixelHeight > 0 && properties?.Height > loadProperties?.MaxDecodePixelHeight) { if (loadProperties.DpiScale != null) { bitmap.DecodePixelHeight = Convert.ToInt32(loadProperties.MaxDecodePixelHeight * loadProperties.DpiScale.Value.DpiScaleY); } else { bitmap.DecodePixelHeight = loadProperties.MaxDecodePixelHeight; } } if (bitmap.DecodePixelHeight != 0 && bitmap.DecodePixelWidth == 0) { bitmap.DecodePixelWidth = (int)Math.Round(aspect.GetWidth(bitmap.DecodePixelHeight)); } else if (bitmap.DecodePixelWidth != 0 && bitmap.DecodePixelHeight == 0) { bitmap.DecodePixelHeight = (int)Math.Round(aspect.GetHeight(bitmap.DecodePixelWidth)); } bitmap.StreamSource = stream; bitmap.CacheOption = BitmapCacheOption.OnLoad; bitmap.CreateOptions = BitmapCreateOptions.IgnoreColorProfile; bitmap.EndInit(); bitmap.Freeze(); return(bitmap); } catch (Exception e) { logger.Error(e, "Failed to create bitmap from stream."); return(null); } }
public void GetWidthTest(double height, double width, AspectRatio ratio) { Assert.AreEqual(width, ratio.GetWidth(height)); }