Ejemplo n.º 1
0
        public static Stream GetResizedImage(ImageMediaSource src, int?maxWidth, int?maxHeight)
        {
            // load file
            if (!src.Exists)
            {
                Log.Info("Requested resized image for non-existing source {0}", src.GetDebugName());
                WCFUtil.SetResponseCode(System.Net.HttpStatusCode.NotFound);
                return(Stream.Null);
            }

            // create cache path
            string filename = String.Format("resize_{0}_{1}_{2}.jpg", src.GetUniqueIdentifier(), maxWidth, maxHeight);

            // check for existence on disk
            if (!cache.Contains(filename))
            {
                Image orig;
                using (var impersonator = src.GetImpersonator())
                {
                    orig = Image.FromStream(src.Retrieve());
                }

                if (!ResizeImage(orig, cache.GetPath(filename), maxWidth, maxHeight))
                {
                    WCFUtil.SetResponseCode(System.Net.HttpStatusCode.InternalServerError);
                    return(Stream.Null);
                }
            }

            return(StreamImage(new ImageMediaSource(cache.GetPath(filename))));
        }
Ejemplo n.º 2
0
        private static Func <Stream> ProcessAndCacheImage(ImageMediaSource src, int?maxWidth, int?maxHeight, string borders, string format)
        {
            // if it's already in the cache, use that file
            string filename = String.Format("stream_{0}_{1}_{2}_{3}.{4}", src.GetUniqueIdentifier(), maxWidth, maxHeight, borders, format);

            if (cache.Contains(filename))
            {
                if (src.GetFileInfo().LastModifiedTime > cache.GetLastModifiedTime(cache.GetPath(filename)))
                {
                    cache.Invalidate(filename);
                }
                else
                {
                    return(() => new FileStream(cache.GetPath(filename), FileMode.Open, FileAccess.Read, FileShare.Read));
                }
            }

            // otherwise, resize if needed and save to cache
            try
            {
                bool hasToResize = maxWidth.HasValue || maxHeight.HasValue;
                bool hasToRecode = format != src.Extension.Substring(1);

                if (!hasToResize && !hasToRecode)
                {
                    return(() => src.Retrieve());
                }

                // process and save to cache
                using (var stream = src.Retrieve())
                {
                    var image = hasToResize ? ResizeImage(stream, maxWidth, maxHeight, borders) : Image.FromStream(stream);
                    SaveImageToFile(image, cache.GetPath(filename), format);
                    image.Dispose();
                }

                return(() => new FileStream(cache.GetPath(filename), FileMode.Open, FileAccess.Read, FileShare.Read));
            }
            catch (Exception ex)
            {
                Log.Warn(String.Format("Failed to process and cache image {0}", src.GetDebugName()), ex);
                return(null);
            }
        }
Ejemplo n.º 3
0
        public static bool CacheImage(ImageMediaSource src, int? maxWidth, int? maxHeight, string borders, string format)
        {
            if (!src.Exists)
            {
                Log.Info("Tried to request image from non-existing source {0}", src.GetDebugName());
                return false;
            }

            if (borders != null && (!maxWidth.HasValue || !maxHeight.HasValue))
            {
                Log.Error("RequestImage() called with a borders value but width or height is null");
                return false;
            }

            if (format == null)
                format = src.Extension.Substring(1);

            return ProcessAndCacheImage(src, maxWidth, maxHeight, borders, format) != null;
        }
Ejemplo n.º 4
0
        private static Stream StreamPostprocessedImage(ImageMediaSource src, int?maxWidth, int?maxHeight, string borders, string format)
        {
            if (!src.Exists)
            {
                Log.Info("Tried to stream image from non-existing source {0}", src.GetDebugName());
                WCFUtil.SetResponseCode(HttpStatusCode.NotFound);
                return(Stream.Null);
            }

            if (borders != null && (!maxWidth.HasValue || !maxHeight.HasValue))
            {
                Log.Error("ResizeImage() called with a borders value but width or height is null");
                WCFUtil.SetResponseCode(HttpStatusCode.BadRequest);
                return(Stream.Null);
            }

            if (format == null)
            {
                format = src.Extension.Substring(1);
            }

            Func <Stream> streamFactory = ProcessAndCacheImage(src, maxWidth, maxHeight, borders, format);

            if (streamFactory == null)
            {
                return(Stream.Null);
            }

            try
            {
                // return image to client
                WCFUtil.AddHeader(HttpResponseHeader.CacheControl, "public, max-age=5184000, s-maxage=5184000");
                WCFUtil.SetContentType(GetMime(format));
                return(streamFactory());
            }
            catch (Exception ex)
            {
                Log.Warn(String.Format("Failed to post-process and stream image {0}", src.GetDebugName()), ex);
                return(Stream.Null);
            }
        }
Ejemplo n.º 5
0
        public static bool CacheImage(ImageMediaSource src, int?maxWidth, int?maxHeight, string borders, string format)
        {
            if (!src.Exists)
            {
                Log.Info("Tried to request image from non-existing source {0}", src.GetDebugName());
                return(false);
            }

            if (borders != null && (!maxWidth.HasValue || !maxHeight.HasValue))
            {
                Log.Error("RequestImage() called with a borders value but width or height is null");
                return(false);
            }

            if (format == null)
            {
                format = src.Extension.Substring(1);
            }

            return(ProcessAndCacheImage(src, maxWidth, maxHeight, borders, format) != null);
        }
Ejemplo n.º 6
0
        private static Stream StreamImage(ImageMediaSource src)
        {
            if (!src.Exists)
            {
                Log.Info("Tried to stream image from non-existing source {0}", src.GetDebugName());
                WCFUtil.SetResponseCode(System.Net.HttpStatusCode.NotFound);
                return(Stream.Null);
            }

            Dictionary <string, string> commonMimeTypes = new Dictionary <string, string>()
            {
                { ".jpeg", "image/jpeg" },
                { ".jpg", "image/jpeg" },
                { ".png", "image/png" },
                { ".gif", "image/gif" },
                { ".bmp", "image/x-ms-bmp" },
            };
            string mime = commonMimeTypes.ContainsKey(src.Extension) ? commonMimeTypes[src.Extension] : "application/octet-stream";

            WCFUtil.SetContentType(mime);

            return(src.Retrieve());
        }
Ejemplo n.º 7
0
        public static Stream GetResizedImage(ImageMediaSource src, int?maxWidth, int?maxHeight)
        {
            // load file
            if (!src.Exists)
            {
                Log.Info("Requested resized image for non-existing source {0}", src.GetDebugName());
                WCFUtil.SetResponseCode(System.Net.HttpStatusCode.NotFound);
                return(Stream.Null);
            }

            // create cache path
            string tmpDir = Path.Combine(Path.GetTempPath(), "MPExtended", "imagecache");

            if (!Directory.Exists(tmpDir))
            {
                Directory.CreateDirectory(tmpDir);
            }
            string cachedPath = Path.Combine(tmpDir, String.Format("rs_{0}_{1}_{2}.jpg", src.GetUniqueIdentifier(), maxWidth, maxHeight));

            // check for existence on disk
            if (!File.Exists(cachedPath))
            {
                Image orig;
                using (var impersonator = src.GetImpersonator())
                {
                    orig = Image.FromStream(src.Retrieve());
                }

                if (!ResizeImage(orig, cachedPath, maxWidth, maxHeight))
                {
                    WCFUtil.SetResponseCode(System.Net.HttpStatusCode.InternalServerError);
                    return(Stream.Null);
                }
            }

            return(StreamImage(new ImageMediaSource(cachedPath)));
        }
Ejemplo n.º 8
0
        public static Stream GetResizedImage(ImageMediaSource src, int? maxWidth, int? maxHeight)
        {
            // load file
            if (!src.Exists)
            {
                Log.Info("Requested resized image for non-existing source {0}", src.GetDebugName());
                WCFUtil.SetResponseCode(System.Net.HttpStatusCode.NotFound);
                return Stream.Null;
            }

            // create cache path
            string filename = String.Format("resize_{0}_{1}_{2}.jpg", src.GetUniqueIdentifier(), maxWidth, maxHeight);

            // check for existence on disk
            if (!cache.Contains(filename))
            {
                Image orig;
                using (var impersonator = src.GetImpersonator())
                {
                    orig = Image.FromStream(src.Retrieve());
                }

                if (!ResizeImage(orig, cache.GetPath(filename), ImageFormat.Jpeg, maxWidth, maxHeight))
                {
                    WCFUtil.SetResponseCode(System.Net.HttpStatusCode.InternalServerError);
                    return Stream.Null;
                }
            }

            return StreamImage(new ImageMediaSource(cache.GetPath(filename)));
        }
Ejemplo n.º 9
0
 public static Stream GetResizedImage(ImageMediaSource src, int?maxWidth, int?maxHeight, string borders, string format)
 {
     return(StreamPostprocessedImage(src, maxWidth, maxHeight, borders, format));
 }
Ejemplo n.º 10
0
 public static Stream GetImage(ImageMediaSource src, string format)
 {
     return(StreamPostprocessedImage(src, null, null, null, format));
 }
Ejemplo n.º 11
0
 public static Stream GetImage(ImageMediaSource source)
 {
     return(StreamImage(source));
 }
Ejemplo n.º 12
0
        private static Stream StreamPostprocessedImage(ImageMediaSource src, int? maxWidth, int? maxHeight, string borders, string format)
        {
            if (!src.Exists)
            {
                Log.Info("Tried to stream image from non-existing source {0}", src.GetDebugName());
                WCFUtil.SetResponseCode(HttpStatusCode.NotFound);
                return Stream.Null;
            }

            if (borders != null && (!maxWidth.HasValue || !maxHeight.HasValue))
            {
                Log.Error("ResizeImage() called with a borders value but width or height is null");
                WCFUtil.SetResponseCode(HttpStatusCode.BadRequest);
                return Stream.Null;
            }

            if (format == null)
                format = src.Extension.Substring(1);

            Func<Stream> streamFactory = ProcessAndCacheImage(src, maxWidth, maxHeight, borders, format);
            if (streamFactory == null)
                return Stream.Null;

            try
            {
                // return image to client
                WCFUtil.AddHeader(HttpResponseHeader.CacheControl, "public, max-age=5184000, s-maxage=5184000");
                WCFUtil.SetContentType(GetMime(format));
                return streamFactory();
            }
            catch (Exception ex)
            {
                Log.Warn(String.Format("Failed to post-process and stream image {0}", src.GetDebugName()), ex);
                return Stream.Null;
            }
        }
Ejemplo n.º 13
0
        public static Stream GetResizedImage(ImageMediaSource src, int? maxWidth, int? maxHeight)
        {
            // load file
            if (!src.Exists)
            {
                Log.Info("Requested resized image for non-existing source {0}", src.GetDebugName());
                WCFUtil.SetResponseCode(System.Net.HttpStatusCode.NotFound);
                return Stream.Null;
            }

            // create cache path
            string tmpDir = Path.Combine(Path.GetTempPath(), "MPExtended", "imagecache");
            if (!Directory.Exists(tmpDir))
                Directory.CreateDirectory(tmpDir);
            string cachedPath = Path.Combine(tmpDir, String.Format("rs_{0}_{1}_{2}.jpg", src.GetUniqueIdentifier(), maxWidth, maxHeight));

            // check for existence on disk
            if (!File.Exists(cachedPath))
            {
                Image orig;
                using (var impersonator = src.GetImpersonator())
                {
                    orig = Image.FromStream(src.Retrieve());
                }

                if (!ResizeImage(orig, cachedPath, maxWidth, maxHeight))
                {
                    WCFUtil.SetResponseCode(System.Net.HttpStatusCode.InternalServerError);
                    return Stream.Null;
                }
            }

            return StreamImage(new ImageMediaSource(cachedPath));
        }
Ejemplo n.º 14
0
        private static Stream StreamPostprocessedImage(ImageMediaSource src, int? maxWidth, int? maxHeight, string borders, string format)
        {
            if (!src.Exists)
            {
                Log.Info("Tried to stream image from non-existing source {0}", src.GetDebugName());
                WCFUtil.SetResponseCode(HttpStatusCode.NotFound);
                return Stream.Null;
            }

            if (borders != null && (!maxWidth.HasValue || !maxHeight.HasValue))
            {
                Log.Error("ResizeImage() called with a borders value but width or height is null");
                WCFUtil.SetResponseCode(HttpStatusCode.BadRequest);
                return Stream.Null;
            }

            if (format == null)
                format = src.Extension.Substring(1);

            // return from cache if possible
            string filename = String.Format("stream_{0}_{1}_{2}_{3}.{4}", src.GetUniqueIdentifier(), maxWidth, maxHeight, borders, format);
            if (cache.Contains(filename))
            {
                if (src.GetFileInfo().LastModifiedTime > cache.GetLastModifiedTime(cache.GetPath(filename)))
                {
                    cache.Invalidate(filename);
                }
                else
                {
                    WCFUtil.AddHeader(HttpResponseHeader.CacheControl, "public, max-age=5184000, s-maxage=5184000"); // not really sure why 2 months exactly
                    WCFUtil.SetContentType(GetMime(Path.GetExtension(filename)));
                    return new FileStream(cache.GetPath(filename), FileMode.Open, FileAccess.Read, FileShare.Read);
                }
            }

            try
            {
                bool hasToResize = maxWidth.HasValue || maxHeight.HasValue;
                bool hasToRecode = format != src.Extension.Substring(1);

                if (!hasToResize && !hasToRecode)
                {
                    WCFUtil.AddHeader(HttpResponseHeader.CacheControl, "public, max-age=5184000, s-maxage=5184000");
                    WCFUtil.SetContentType(GetMime(src.Extension));
                    return src.Retrieve();
                }

                // save image to cache
                string path = cache.GetPath(String.Format("stream_{0}_{1}_{2}_{3}.{4}", src.GetUniqueIdentifier(), maxWidth, maxHeight, borders, format));
                using (var stream = src.Retrieve())
                {
                    var image = hasToResize ? ResizeImage(stream, maxWidth, maxHeight, borders) : Image.FromStream(stream);
                    SaveImageToFile(image, path, format);
                    image.Dispose();
                }

                // return image to client
                WCFUtil.AddHeader(HttpResponseHeader.CacheControl, "public, max-age=5184000, s-maxage=5184000");
                WCFUtil.SetContentType(GetCodecInfo(format).MimeType);
                return new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);
            }
            catch (Exception ex)
            {
                Log.Warn(String.Format("Failed to post-process and stream image {0}", src.GetDebugName()), ex);
                return Stream.Null;
            }
        }
Ejemplo n.º 15
0
 public static Stream GetResizedImage(ImageMediaSource src, int? maxWidth, int? maxHeight, string borders, string format)
 {
     return StreamPostprocessedImage(src, maxWidth, maxHeight, borders, format);
 }
Ejemplo n.º 16
0
 public static Stream GetImage(ImageMediaSource src, string format)
 {
     return StreamPostprocessedImage(src, null, null, null, format);
 }
Ejemplo n.º 17
0
        private static Stream StreamPostprocessedImage(ImageMediaSource src, int? maxWidth, int? maxHeight, string borders, string format)
        {
            if (!src.Exists)
            {
                Log.Info("Tried to stream image from non-existing source {0}", src.GetDebugName());
                WCFUtil.SetResponseCode(HttpStatusCode.NotFound);
                return Stream.Null;
            }

            if (borders != null && !maxWidth.HasValue && !maxHeight.HasValue)
            {
                Log.Error("ResizeImage() called with a broders value but width or height is null");
                WCFUtil.SetResponseCode(HttpStatusCode.BadRequest);
                return Stream.Null;
            }

            if (format == null)
                format = src.Extension.Substring(1);

            // return from cache if possible
            string filename = String.Format("stream_{0}_{1}_{2}_{3}.{4}", src.GetUniqueIdentifier(), maxWidth, maxHeight, borders, format);
            if (cache.Contains(filename))
            {
                WCFUtil.SetContentType(Path.GetExtension(filename));
                return new FileStream(cache.GetPath(filename), FileMode.Open, FileAccess.Read, FileShare.Read);
            }

            try
            {
                bool hasToResize = maxWidth.HasValue || maxHeight.HasValue;
                bool hasToRecode = format != src.Extension.Substring(1);

                if (!hasToResize && !hasToRecode)
                {
                    WCFUtil.SetContentType(GetMime(src.Extension));
                    return src.Retrieve();
                }

                var image = hasToResize ? ResizeImage(src, maxWidth, maxHeight, borders) : Image.FromStream(src.Retrieve());
                string path = cache.GetPath(String.Format("stream_{0}_{1}_{2}_{3}.{4}", src.GetUniqueIdentifier(), maxWidth, maxHeight, borders, format));
                SaveImageToFile(image, path, format);
                image.Dispose();
                WCFUtil.SetContentType(GetCodecInfo(format).MimeType);
                return new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);
            }
            catch (Exception ex)
            {
                Log.Warn(String.Format("Failed to post-process and stream image {0}", src.GetDebugName()), ex);
                return Stream.Null;
            }
        }
Ejemplo n.º 18
0
        private static Image ResizeImage(ImageMediaSource src, int? maxWidth, int? maxHeight, string borders)
        {
            using (var origImage = Image.FromStream(src.Retrieve()))
            {
                Resolution newSize = Resolution.Calculate(origImage.Width, origImage.Height, maxWidth, maxHeight, 1);
                int bitmapWidth = !String.IsNullOrEmpty(borders) ? maxWidth.Value : newSize.Width;
                int bitmapHeight = !String.IsNullOrEmpty(borders) ? maxHeight.Value : newSize.Height;

                Bitmap newImage = new Bitmap(bitmapWidth, bitmapHeight, PixelFormat.Format32bppArgb);
                using (Graphics graphic = Graphics.FromImage(newImage))
                {
                    graphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
                    graphic.SmoothingMode = SmoothingMode.HighQuality;
                    graphic.CompositingQuality = CompositingQuality.HighQuality;
                    graphic.CompositingMode = CompositingMode.SourceCopy;
                    graphic.PixelOffsetMode = PixelOffsetMode.HighQuality;

                    if (!String.IsNullOrEmpty(borders))
                        graphic.FillRectangle(new SolidBrush(ColorTranslator.FromHtml("#" + borders)), 0, 0, bitmapWidth, bitmapHeight);

                    int leftOffset = !String.IsNullOrEmpty(borders) ? (maxWidth.Value - newSize.Width) / 2 : 0;
                    int heightOffset = !String.IsNullOrEmpty(borders) ? (maxHeight.Value - newSize.Height) / 2 : 0;
                    graphic.DrawImage(origImage, leftOffset, heightOffset, newSize.Width, newSize.Height);
                }

                return newImage;
            }
        }
Ejemplo n.º 19
0
 public static Stream GetImage(ImageMediaSource source)
 {
     return StreamImage(source);
 }
Ejemplo n.º 20
0
        private static Stream StreamPostprocessedImage(ImageMediaSource src, int?maxWidth, int?maxHeight, string borders, string format)
        {
            if (!src.Exists)
            {
                Log.Info("Tried to stream image from non-existing source {0}", src.GetDebugName());
                WCFUtil.SetResponseCode(HttpStatusCode.NotFound);
                return(Stream.Null);
            }

            if (borders != null && (!maxWidth.HasValue || !maxHeight.HasValue))
            {
                Log.Error("ResizeImage() called with a borders value but width or height is null");
                WCFUtil.SetResponseCode(HttpStatusCode.BadRequest);
                return(Stream.Null);
            }

            if (format == null)
            {
                format = src.Extension.Substring(1);
            }

            // return from cache if possible
            string filename = String.Format("stream_{0}_{1}_{2}_{3}.{4}", src.GetUniqueIdentifier(), maxWidth, maxHeight, borders, format);

            if (cache.Contains(filename))
            {
                if (src.GetFileInfo().LastModifiedTime > cache.GetLastModifiedTime(cache.GetPath(filename)))
                {
                    cache.Invalidate(filename);
                }
                else
                {
                    WCFUtil.AddHeader(HttpResponseHeader.CacheControl, "public, max-age=5184000, s-maxage=5184000"); // not really sure why 2 months exactly
                    WCFUtil.SetContentType(GetMime(Path.GetExtension(filename)));
                    return(new FileStream(cache.GetPath(filename), FileMode.Open, FileAccess.Read, FileShare.Read));
                }
            }

            try
            {
                bool hasToResize = maxWidth.HasValue || maxHeight.HasValue;
                bool hasToRecode = format != src.Extension.Substring(1);

                if (!hasToResize && !hasToRecode)
                {
                    WCFUtil.AddHeader(HttpResponseHeader.CacheControl, "public, max-age=5184000, s-maxage=5184000");
                    WCFUtil.SetContentType(GetMime(src.Extension));
                    return(src.Retrieve());
                }

                // save image to cache
                string path = cache.GetPath(String.Format("stream_{0}_{1}_{2}_{3}.{4}", src.GetUniqueIdentifier(), maxWidth, maxHeight, borders, format));
                using (var stream = src.Retrieve())
                {
                    var image = hasToResize ? ResizeImage(stream, maxWidth, maxHeight, borders) : Image.FromStream(stream);
                    SaveImageToFile(image, path, format);
                    image.Dispose();
                }

                // return image to client
                WCFUtil.AddHeader(HttpResponseHeader.CacheControl, "public, max-age=5184000, s-maxage=5184000");
                WCFUtil.SetContentType(GetCodecInfo(format).MimeType);
                return(new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read));
            }
            catch (Exception ex)
            {
                Log.Warn(String.Format("Failed to post-process and stream image {0}", src.GetDebugName()), ex);
                return(Stream.Null);
            }
        }
Ejemplo n.º 21
0
        private static Stream StreamImage(ImageMediaSource src)
        {
            if (!src.Exists)
            {
                Log.Info("Tried to stream image from non-existing source {0}", src.GetDebugName());
                WCFUtil.SetResponseCode(System.Net.HttpStatusCode.NotFound);
                return Stream.Null;
            }

            Dictionary<string, string> commonMimeTypes = new Dictionary<string, string>() {
                { ".jpeg", "image/jpeg" },
                { ".jpg", "image/jpeg" },
                { ".png", "image/png" },
                { ".gif", "image/gif" },
                { ".bmp", "image/x-ms-bmp" },
            };
            string mime = commonMimeTypes.ContainsKey(src.Extension) ? commonMimeTypes[src.Extension] : "application/octet-stream";
            WebOperationContext.Current.OutgoingResponse.ContentType = mime;

            return src.Retrieve();
        }
Ejemplo n.º 22
0
        private static Func<Stream> ProcessAndCacheImage(ImageMediaSource src, int? maxWidth, int? maxHeight, string borders, string format)
        {
            // if it's already in the cache, use that file
            string filename = String.Format("stream_{0}_{1}_{2}_{3}.{4}", src.GetUniqueIdentifier(), maxWidth, maxHeight, borders, format);
            if (cache.Contains(filename))
            {
                if (src.GetFileInfo().LastModifiedTime > cache.GetLastModifiedTime(cache.GetPath(filename)))
                {
                    cache.Invalidate(filename);
                }
                else
                {
                    return () => new FileStream(cache.GetPath(filename), FileMode.Open, FileAccess.Read, FileShare.Read);
                }
            }

            // otherwise, resize if needed and save to cache
            try
            {
                bool hasToResize = maxWidth.HasValue || maxHeight.HasValue;
                bool hasToRecode = format != src.Extension.Substring(1);

                if (!hasToResize && !hasToRecode)
                    return () => src.Retrieve();

                // process and save to cache
                using (var stream = src.Retrieve())
                {
                    var image = hasToResize ? ResizeImage(stream, maxWidth, maxHeight, borders) : Image.FromStream(stream);
                    SaveImageToFile(image, cache.GetPath(filename), format);
                    image.Dispose();
                }

                return () => new FileStream(cache.GetPath(filename), FileMode.Open, FileAccess.Read, FileShare.Read);
            }
            catch (Exception ex)
            {
                Log.Warn(String.Format("Failed to process and cache image {0}", src.GetDebugName()), ex);
                return null;
            }
        }