コード例 #1
0
        protected virtual ProcessImageQuery BuildImageQuery()
        {
            var query = new ProcessImageQuery();

            if (Size > 0)
            {
                query.MaxSize = Size.Value;
            }

            if (Width > 0)
            {
                query.MaxWidth = Width.Value;
            }

            if (Height > 0)
            {
                query.MaxHeight = Height.Value;
            }

            if (ResizeMode.HasValue)
            {
                query.ScaleMode = ResizeMode.Value.ToString().ToLower();
            }

            if (AnchorPosition.HasValue)
            {
                query.AnchorPosition = AnchorPosition.Value.ToString().Kebaberize();
            }

            return(query);
        }
コード例 #2
0
        private async Task <ProcessImageQuery> CreateImageQuery(HttpContext context, string mimeType, string extension)
        {
            if (extension == "svg")
            {
                return(new ProcessImageQuery {
                    Format = "svg"
                });
            }

            // TODO: (mc) implement "raw" image handling later
            //if (qs.GetValues(null).Contains("raw", StringComparer.OrdinalIgnoreCase) || qs["raw"] != null)
            //{
            //	return null;
            //}

            var query = new ProcessImageQuery(null, context.Request.Query);

            //if (query.Quality == null)
            //{
            //    query.Quality = _mediaSettings.DefaultImageQuality;
            //}

            await _eventPublisher.PublishAsync(new ImageQueryCreatedEvent(query, context, mimeType, extension));

            return(query);
        }
コード例 #3
0
        private async Task <byte[]> ProcessAndPutToCacheAsync(CachedImageResult cachedImage, byte[] buffer, ProcessImageQuery query)
        {
            if (!query.NeedsProcessing())
            {
                await _imageCache.PutAsync(cachedImage, buffer);

                return(buffer);
            }
            else
            {
                var processQuery = new ProcessImageQuery(query)
                {
                    Source        = buffer,
                    Format        = query.Format ?? cachedImage.Extension,
                    FileName      = cachedImage.FileName,
                    DisposeSource = true
                };

                using (var result = _imageProcessor.ProcessImage(processQuery))
                {
                    var outBuffer = result.OutputStream.GetBuffer();
                    await _imageCache.PutAsync(cachedImage, outBuffer);

                    if (cachedImage.Extension != result.FileExtension)
                    {
                        cachedImage.Path      = Path.ChangeExtension(cachedImage.Path, result.FileExtension);
                        cachedImage.Extension = result.FileExtension;
                    }

                    Logger.DebugFormat($"Processed image '{cachedImage.FileName}' in {result.ProcessTimeMs} ms.", null);

                    return(outBuffer);
                }
            }
        }
コード例 #4
0
ファイル: MediaController.cs プロジェクト: OLAPADE1/commerce
        protected virtual ProcessImageQuery CreateImageQuery(string mimeType, string extension)
        {
            var qs = Request.QueryString;

            // TODO: (mc) implement "raw" image handling later
            //if (qs.GetValues(null).Contains("raw", StringComparer.OrdinalIgnoreCase) || qs["raw"] != null)
            //{
            //	return null;
            //}

            var query = new ProcessImageQuery(null, qs);

            if (query.MaxWidth == null && query.MaxHeight == null && query.Contains("size"))
            {
                int size = query["size"].Convert <int>();
                query.MaxWidth  = size;
                query.MaxHeight = size;

                query.Remove("size");
            }

            if (query.Quality == null)
            {
                query.Quality = _mediaSettings.DefaultImageQuality;
            }

            _eventPublisher.Publish(new ImageQueryCreatedEvent(query, this.HttpContext, mimeType, extension));

            return(query);
        }
コード例 #5
0
ファイル: MediaController.cs プロジェクト: krreddy123/appcode
        protected virtual ProcessImageQuery CreateImageQuery(string mimeType, string extension)
        {
            if (extension == "svg")
            {
                return(new ProcessImageQuery {
                    Format = "svg"
                });
            }

            var qs = Request.QueryString;

            // TODO: (mc) implement "raw" image handling later
            //if (qs.GetValues(null).Contains("raw", StringComparer.OrdinalIgnoreCase) || qs["raw"] != null)
            //{
            //	return null;
            //}

            var query = new ProcessImageQuery(null, qs);

            if (query.Quality == null)
            {
                query.Quality = _mediaSettings.DefaultImageQuality;
            }

            _eventPublisher.Publish(new ImageQueryCreatedEvent(query, this.HttpContext, mimeType, extension));

            return(query);
        }
コード例 #6
0
        protected override async Task ProcessImageAsync(MediaHandlerContext context, CachedImage cachedImage, Stream inputStream)
        {
            var processQuery = new ProcessImageQuery(context.ImageQuery)
            {
                Source        = inputStream,
                Format        = context.ImageQuery.Format ?? cachedImage.Extension,
                FileName      = cachedImage.FileName,
                DisposeSource = false
            };

            using (var result = await _imageProcessor.ProcessImageAsync(processQuery, false))
            {
                Logger.Debug($"Processed image '{cachedImage.FileName}' in {result.ProcessTimeMs} ms.");

                var ext = result.Image.Format.DefaultExtension;

                if (!cachedImage.Extension.EqualsNoCase(ext))
                {
                    // jpg <> jpeg
                    cachedImage.Path      = Path.ChangeExtension(cachedImage.Path, ext);
                    cachedImage.Extension = ext;
                }

                context.ResultImage = result.Image;
            }
        }
コード例 #7
0
 public static string GenerateUrl(
     this IMediaUrlGenerator service,
     MediaFileInfo file,
     ProcessImageQuery imageQuery,
     string host     = null,
     bool doFallback = true)
 {
     return(service.GenerateUrl(file, imageQuery != null ? imageQuery.ToQueryString() : QueryString.Empty, host, doFallback));
 }
コード例 #8
0
        public static string GetFallbackUrl(this IMediaService service, int thumbnailSize = 0)
        {
            ProcessImageQuery query = thumbnailSize > 0
                ? new ProcessImageQuery {
                MaxSize = thumbnailSize
            }
                : null;

            return(service.GetUrl((MediaFileInfo)null, query, null, true));
        }
コード例 #9
0
        public static string GetUrl(this IMediaService service, MediaFileInfo file, int thumbnailSize, string host = null, bool doFallback = true)
        {
            ProcessImageQuery query = thumbnailSize > 0
                ? new ProcessImageQuery {
                MaxSize = thumbnailSize
            }
                : null;

            return(service.GetUrl(file, query, host, doFallback));
        }
コード例 #10
0
        public static async Task <string> GetUrlAsync(this IMediaService service, int?fileId, int thumbnailSize, string host = null, bool doFallback = true)
        {
            ProcessImageQuery query = thumbnailSize > 0
                ? new ProcessImageQuery {
                MaxSize = thumbnailSize
            }
                : null;

            return(service.GetUrl(await service.GetFileByIdAsync(fileId ?? 0, MediaLoadFlags.AsNoTracking), query, host, doFallback));
        }
コード例 #11
0
        private void ImageResize(string path, string dest, int maxWidth, int maxHeight, bool notify = true)
        {
            if (dest.IsEmpty())
            {
                return;
            }

            if (maxWidth == 0 && maxHeight == 0)
            {
                maxWidth  = _mediaSettings.Value.MaximumImageSize;
                maxHeight = _mediaSettings.Value.MaximumImageSize;
            }

            var buffer = System.IO.File.ReadAllBytes(path);

            var query = new ProcessImageQuery(buffer)
            {
                Quality          = _mediaSettings.Value.DefaultImageQuality,
                Format           = Path.GetExtension(path).Trim('.').ToLower(),
                IsValidationMode = true,
                Notify           = notify
            };

            var originalSize = ImageHeader.GetDimensions(buffer, MimeTypes.MapNameToMimeType(path));

            if (originalSize.IsEmpty || (originalSize.Height <= maxHeight && originalSize.Width <= maxWidth))
            {
                // Give subscribers the chance to (pre)-process
                var evt = new ImageUploadValidatedEvent(query, originalSize);
                _eventPublisher.Publish(evt);

                if (evt.ResultBuffer != null)
                {
                    System.IO.File.WriteAllBytes(dest, evt.ResultBuffer);
                }

                return;
            }

            if (maxWidth > 0)
            {
                query.MaxWidth = maxWidth;
            }
            if (maxHeight > 0)
            {
                query.MaxHeight = maxHeight;
            }

            using (var result = _imageProcessor.Value.ProcessImage(query))
            {
                buffer = result.OutputStream.GetBuffer();
                System.IO.File.WriteAllBytes(dest, buffer);
            }
        }
コード例 #12
0
ファイル: MediaService.cs プロジェクト: webtrad3r/Smartstore
        protected async Task <AsyncOut <IImage> > ProcessImage(MediaFile file, Stream inStream)
        {
            var originalSize = Size.Empty;
            var format       = _imageProcessor.Factory.FindFormatByExtension(file.Extension) ?? new UnsupportedImageFormat(file.MimeType, file.Extension);

            try
            {
                originalSize = ImageHeader.GetPixelSize(inStream, file.MimeType);
            }
            catch
            {
            }

            IImage outImage;

            if (format is UnsupportedImageFormat)
            {
                outImage = new ImageWrapper(inStream, originalSize, format);
                return(new AsyncOut <IImage>(true, outImage));
            }

            var maxSize = _mediaSettings.MaximumImageSize;

            var query = new ProcessImageQuery(inStream)
            {
                Format               = file.Extension,
                DisposeSource        = true,
                ExecutePostProcessor = ImagePostProcessingEnabled,
                IsValidationMode     = true
            };

            if (originalSize.IsEmpty || (originalSize.Height <= maxSize && originalSize.Width <= maxSize))
            {
                // Give subscribers the chance to (pre)-process
                var evt = new ImageUploadedEvent(query, originalSize);
                await _eventPublisher.PublishAsync(evt);

                outImage = evt.ResultImage ?? new ImageWrapper(inStream, originalSize, format);

                return(new AsyncOut <IImage>(true, outImage));
            }

            query.MaxSize = maxSize;

            using (var result = await _imageProcessor.ProcessImageAsync(query, false))
            {
                outImage = result.Image;
                return(new AsyncOut <IImage>(true, outImage));
            }
        }
コード例 #13
0
        protected virtual ProcessImageQuery CreateImageQuery(string mimeType, string extension)
        {
            var query = new ProcessImageQuery(null, Request.QueryString);

            if (query.MaxWidth == null && query.MaxHeight == null && query.Contains("size"))
            {
                int size = query["size"].Convert <int>();
                query.MaxWidth  = size;
                query.MaxHeight = size;

                query.Remove("size");
            }

            if (query.Quality == null)
            {
                query.Quality = _mediaSettings.DefaultImageQuality;
            }

            _eventPublisher.Publish(new ImageQueryCreatedEvent(query, this.HttpContext, mimeType, extension));

            return(query);
        }
コード例 #14
0
        protected override void ProcessCore(TagHelperContext context, TagHelperOutput output)
        {
            var query = new ProcessImageQuery();

            if (ImageSize > 0)
            {
                query.MaxSize = ImageSize.Value;
            }

            if (ImageWidth > 0)
            {
                query.MaxWidth = ImageWidth.Value;
            }

            if (ImageHeight > 0)
            {
                query.MaxHeight = ImageHeight.Value;
            }

            if (ImageResizeMode.HasValue)
            {
                query.ScaleMode = ImageResizeMode.Value.ToString().ToLower();
            }

            var src = _urlGenerator.GenerateUrl(File, query.ToQueryString());

            output.Attributes.SetAttribute("src", src);

            if (File.Alt.HasValue())
            {
                output.Attributes.SetAttributeNoReplace("alt", File.Alt);
            }

            if (File.TitleAttribute.HasValue())
            {
                output.Attributes.SetAttributeNoReplace("title", File.TitleAttribute);
            }
        }
コード例 #15
0
        public static string Media(this UrlHelper urlHelper, MediaFileInfo file, ProcessImageQuery query, string host = null, bool doFallback = true)
        {
            var mediaService = EngineContext.Current.Resolve <IMediaService>();

            return(mediaService.GetUrl(file, query, host, doFallback));
        }
コード例 #16
0
        private async Task <ActionResult> HandleImage(
            ProcessImageQuery query,
            CachedImageResult cachedImage,
            string nameWithoutExtension,
            string mime,
            string extension,
            Func <string, Task <byte[]> > getSourceBuffer)
        {
            string prevMime = null;

            if (extension != cachedImage.Extension)
            {
                // The query requests another format.
                // Adjust extension and mime type fo proper ETag creation.
                extension = cachedImage.Extension;
                prevMime  = mime;
                mime      = MimeTypes.MapNameToMimeType(cachedImage.FileName);
            }

            if (cachedImage.Exists)
            {
                if (ETagMatches(nameWithoutExtension, mime, cachedImage.LastModifiedUtc.Value))
                {
                    return(Content(null));
                }
            }

            var isFaulted = false;

            try
            {
                if (!cachedImage.Exists)
                {
                    // get the async (semaphore) locker specific to this key
                    var keyLock = AsyncLock.Acquire("lock" + cachedImage.Path);

                    // Lock concurrent requests to same resource
                    using (await keyLock.LockAsync())
                    {
                        _imageCache.RefreshInfo(cachedImage);

                        // File could have been processed by another request in the meantime, check again.
                        if (!cachedImage.Exists)
                        {
                            // Call inner function
                            byte[] source = await getSourceBuffer(prevMime);

                            if (source == null)
                            {
                                return(NotFound(mime));
                            }

                            source = await ProcessAndPutToCacheAsync(cachedImage, source, query);

                            return(File(source, mime));
                        }
                    }
                }

                if (Request.HttpMethod == "HEAD")
                {
                    return(new HttpStatusCodeResult(200));
                }

                if (cachedImage.IsRemote && !_streamRemoteMedia)
                {
                    // Redirect to existing remote file
                    Response.ContentType = mime;
                    return(Redirect(_imageCache.GetPublicUrl(cachedImage.Path)));
                }
                else
                {
                    // Open existing stream
                    return(File(cachedImage.File.OpenRead(), mime));
                }
            }
            catch (Exception ex)
            {
                isFaulted = true;
                if (!(ex is ProcessImageException))
                {
                    // ProcessImageException is logged already in ImageProcessor
                    Logger.ErrorFormat(ex, "Error processing media file '{0}'.", cachedImage.Path);
                }
                return(new HttpStatusCodeResult(500, ex.Message));
            }
            finally
            {
                if (!isFaulted)
                {
                    FinalizeRequest(nameWithoutExtension, mime, cachedImage.LastModifiedUtc.GetValueOrDefault());
                }
            }
        }
コード例 #17
0
ファイル: MediaController.cs プロジェクト: OLAPADE1/commerce
        private async Task <ActionResult> HandleImageAsync(
            ProcessImageQuery query,
            CachedImageResult cachedImage,
            string nameWithoutExtension,
            string mime,
            string extension,
            Func <string, Task <byte[]> > getSourceBufferAsync)
        {
            string prevMime = null;

            if (extension != cachedImage.Extension)
            {
                // The query requests another format.
                // Adjust extension and mime type fo proper ETag creation.
                extension = cachedImage.Extension;
                prevMime  = mime;
                mime      = MimeTypes.MapNameToMimeType(cachedImage.FileName);
            }

            try
            {
                if (!cachedImage.Exists)
                {
                    // Lock concurrent requests to same resource
                    using (await KeyedLock.LockAsync("MediaController.HandleImage." + cachedImage.Path))
                    {
                        _imageCache.RefreshInfo(cachedImage);

                        // File could have been processed by another request in the meantime, check again.
                        if (!cachedImage.Exists)
                        {
                            // Call inner function
                            byte[] source = await getSourceBufferAsync(prevMime);

                            if (source == null || source.Length == 0)
                            {
                                return(NotFound(mime));
                            }

                            source = await ProcessAndPutToCacheAsync(cachedImage, source, query);

                            return(new CachedFileResult(mime, cachedImage.LastModifiedUtc.GetValueOrDefault(), () => source, source.LongLength));
                        }
                    }
                }

                if (Request.HttpMethod == "HEAD")
                {
                    return(new HttpStatusCodeResult(200));
                }

                if (cachedImage.IsRemote && !_streamRemoteMedia)
                {
                    // Redirect to existing remote file
                    Response.ContentType = mime;
                    return(Redirect(_imageCache.GetPublicUrl(cachedImage.Path)));
                }
                else
                {
                    // Open existing stream
                    return(new CachedFileResult(cachedImage.File, mime));
                }
            }
            catch (Exception ex)
            {
                if (!(ex is ProcessImageException))
                {
                    // ProcessImageException is logged already in ImageProcessor
                    Logger.ErrorFormat(ex, "Error processing media file '{0}'.", cachedImage.Path);
                }
                return(new HttpStatusCodeResult(500, ex.Message));
            }
        }
コード例 #18
0
 public static async Task <string> GetUrlAsync(this IMediaService service, int?fileId, ProcessImageQuery imageQuery, string host = null, bool doFallback = true)
 {
     return(service.GetUrl(await service.GetFileByIdAsync(fileId ?? 0, MediaLoadFlags.AsNoTracking), imageQuery, host, doFallback));
 }
コード例 #19
0
 protected override string GenerateMediaUrl()
 {
     ImageQuery = BuildImageQuery();
     return(MediaUrlGenerator.GenerateUrl(File, ImageQuery.ToQueryString(), Host, !NoFallback));
 }
コード例 #20
0
ファイル: MediaService.cs プロジェクト: webtrad3r/Smartstore
 public string GetUrl(MediaFileInfo file, ProcessImageQuery imageQuery, string host = null, bool doFallback = true)
 {
     return(_urlGenerator.GenerateUrl(file, imageQuery, host, doFallback));
 }
コード例 #21
0
        public static string Media(this IUrlHelper urlHelper, MediaFileInfo file, ProcessImageQuery query, string host = null, bool doFallback = true)
        {
            var mediaService = urlHelper.ActionContext.HttpContext.RequestServices.GetRequiredService <IMediaService>();

            return(mediaService.GetUrl(file, query, host, doFallback));
        }
コード例 #22
0
        public static Task <string> MediaAsync(this IUrlHelper urlHelper, int?fileId, ProcessImageQuery query, string host = null, bool doFallback = true)
        {
            var mediaService = urlHelper.ActionContext.HttpContext.RequestServices.GetRequiredService <IMediaService>();

            return(mediaService.GetUrlAsync(fileId, query, host, doFallback));
        }
コード例 #23
0
 public static string Media(this UrlHelper urlHelper, int?fileId, ProcessImageQuery query, string host = null, bool doFallback = true)
 {
     return(EngineContext.Current.Resolve <IMediaService>().GetUrl(fileId, query, host, doFallback));
 }