From 3a3655daaa8c22fbe5960907c032a4ee739a9c37 Mon Sep 17 00:00:00 2001 From: Lombiq Date: Fri, 31 Oct 2014 19:50:44 +0100 Subject: [PATCH] #20644: Working around Azure Websites limitation of not being able to use System.Drawing.Image with .ico files. WorkItem: 20644 --- .../Factories/ImageFactory.cs | 32 ++++++++++++++++--- 1 file changed, 28 insertions(+), 4 deletions(-) diff --git a/src/Orchard.Web/Modules/Orchard.MediaLibrary/Factories/ImageFactory.cs b/src/Orchard.Web/Modules/Orchard.MediaLibrary/Factories/ImageFactory.cs index 72764f3a8..e0aafe39f 100644 --- a/src/Orchard.Web/Modules/Orchard.MediaLibrary/Factories/ImageFactory.cs +++ b/src/Orchard.Web/Modules/Orchard.MediaLibrary/Factories/ImageFactory.cs @@ -29,7 +29,7 @@ namespace Orchard.MediaLibrary.Factories { if (!String.IsNullOrEmpty(contentType)) { var contentDefinition = _contentDefinitionManager.GetTypeDefinition(contentType); - if (contentDefinition == null || contentDefinition.Parts.All(x => x.PartDefinition.Name != typeof (ImagePart).Name)) { + if (contentDefinition == null || contentDefinition.Parts.All(x => x.PartDefinition.Name != typeof(ImagePart).Name)) { return null; } } @@ -65,12 +65,36 @@ namespace Orchard.MediaLibrary.Factories { return null; } - using (var image = Image.FromStream(stream)) { - imagePart.Width = image.Width; - imagePart.Height = image.Height; + try { + using (var image = Image.FromStream(stream)) { + imagePart.Width = image.Width; + imagePart.Height = image.Height; + } + } + catch (ArgumentException) { + // Still trying to get .ico dimensions when it's blocked in System.Drawing, see: https://orchard.codeplex.com/workitem/20644 + + if (mimeType != "image/x-icon" && mimeType != "image/vnd.microsoft.icon") { + throw; + } + + TryFillDimensionsForIco(stream, imagePart); } return part; } + + private void TryFillDimensionsForIco(Stream stream, ImagePart imagePart) { + stream.Position = 0; + using (var binaryReader = new BinaryReader(stream)) { + // Reading out the necessary bytes that indicate the image dimensions. For the file format see: + // http://en.wikipedia.org/wiki/ICO_%28file_format%29 + // Reading out leading bytes containing unneded information. + binaryReader.ReadBytes(6); + // Reading out dimensions. If there are multiple icons bundled in the same file then this is the first image. + imagePart.Width = binaryReader.ReadByte(); + imagePart.Height = binaryReader.ReadByte(); + } + } } } \ No newline at end of file