Exemplo n.º 1
0
        /// <summary>
        /// Creates a new ImageMetadata object based on the specified image retriever and save name.
        /// </summary>
        /// <param name="imageRetriever">The image retriever.</param>
        /// <param name="saveName">Name of the save.</param>
        /// <returns>An instance of te image metadata</returns>
        public static ImageMetadata Create(ImageRetriever imageRetriever, string saveName)
        {
            if (imageRetriever == null)
            {
                throw new ArgumentNullException("imageRetriever");
            }

            imageRetriever.EnsureMetadata();

            ImageMetadata retVal = new ImageMetadata();

            string filename = imageRetriever.FileNameWithoutExtension;

            retVal.SaveName = (string.IsNullOrEmpty(saveName)) ? filename : saveName;

            retVal.Extension   = imageRetriever.Extension.ToUpperInvariant();
            retVal.ImageFormat = ImageFormatUtility.GetImageFormatByExtension(retVal.Extension);
            retVal.ContentType = retVal.ImageFormat.GetContentType();

            DateTime lastModifiedDate = imageRetriever.LastModifiedDate;

            retVal.LastModifiedDate = new DateTime(lastModifiedDate.Year,
                                                   lastModifiedDate.Month,
                                                   lastModifiedDate.Day,
                                                   lastModifiedDate.Hour,
                                                   lastModifiedDate.Minute,
                                                   lastModifiedDate.Second,
                                                   DateTimeKind.Utc
                                                   );

            return(retVal);
        }
Exemplo n.º 2
0
        /// <summary>
        /// Creates the image retriever.
        /// </summary>
        /// <param name="source">The source.</param>
        /// <param name="typeName">Name of the type.</param>
        /// <returns>An instance of the image retriever </returns>
        internal static ImageRetriever Create(string source, string typeName)
        {
            if (string.IsNullOrEmpty(typeName))
            {
                throw new ArgumentNullException("typeName");
            }

            ImageRetriever  retVal          = null;
            ConstructorInfo constructorInfo = null;

            readerWriterLockSlim.EnterUpgradeableReadLock();
            try {
                if (!imageRetrieverCache.TryGetValue(typeName, out constructorInfo))
                {
                    Type connectorType = Type.GetType(typeName, false, true);
                    if (connectorType != null && connectorType.IsSubclassOf(typeof(ImageRetriever)))
                    {
                        Type[] argumentTypes = new Type[1];
                        argumentTypes[0] = typeof(string);
                        constructorInfo  = connectorType.GetConstructor(argumentTypes);

                        if (constructorInfo == null)
                        {
                            string errorMessage = string.Format(CultureInfo.InvariantCulture, "The given type: '{0}' does not contain a constructor that takes one argument.", typeName);
                            throw new ArgumentException(errorMessage, "typeName");
                        }

                        readerWriterLockSlim.EnterWriteLock();
                        try {
                            imageRetrieverCache.Add(typeName, constructorInfo);
                        } finally {
                            readerWriterLockSlim.ExitWriteLock();
                        }
                    }
                    else
                    {
                        string errorMessage = string.Format(CultureInfo.InvariantCulture, "The given type: '{0}' can not be found or does not implement the abstract ImageRetriever class.", typeName);
                        throw new ArgumentException(errorMessage, "typeName");
                    }
                }
            } finally {
                readerWriterLockSlim.ExitUpgradeableReadLock();
            }

            retVal = constructorInfo.Invoke(new object[] { source }) as ImageRetriever;

            return(retVal);
        }
Exemplo n.º 3
0
        /// <summary>
        /// Enables processing of HTTP Web requests by a custom HttpHandler that implements the <see cref="T:System.Web.IHttpHandler"/> interface.
        /// </summary>
        /// <param name="context">An <see cref="T:System.Web.HttpContext"/> object that provides references to the intrinsic server objects (for example, Request, Response, Session, and Server) used to service HTTP requests.</param>
        public void ProcessRequest(HttpContext context)
        {
            context.Response.Clear();
            context.Response.Cache.SetCacheability(HttpCacheability.Public);
            context.Response.Cache.SetAllowResponseInBrowserHistory(true);
            context.Response.Cache.SetValidUntilExpires(true);
            context.Response.BufferOutput = false;

            try {
                HttpRequest  request  = context.Request;
                HttpResponse response = context.Response;

                bool leechProtect = request.GetQueryStringValue <bool>("lp", false);

                //validate the request
                if (!request.IsValid(true, leechProtect))
                {
                    throw new HttpException((int)HttpStatusCode.BadRequest, "The request did not pass validation.");
                }


                //retrieve the filepath of the image we would like to retrieve
                string imageSrc = GetImageSourceQueryStringValue(context);

                //create an image retriever and get the file extension
                ImageRetriever imageRetriever = ImageRetrieverFactory.CreateImageRetriever(imageSrc);
                string         filename       = imageRetriever.GetFileNameWithoutExtension();
                string         extension      = imageRetriever.GetExtension().ToUpperInvariant();

                //set the content type of the response
                response.ContentType = GetContentType(extension);

                //set the content-disposition header to the given SaveName or the filename
                string saveName = request.GetQueryStringValue <string>("sn", filename);
                response.AppendHeader("Content-Disposition", string.Concat("inline; filename=\"", saveName, "\""));

                using (MemoryStream memoryStream = new MemoryStream()) {
                    string hash        = request.GetQueryStringValue <string>("ha", null);
                    bool   cacheOutput = request.GetQueryStringValue <bool>("co", false);

                    bool fromCache = false;
                    if (cacheOutput)
                    {
                        object cache = context.Cache[hash];
                        if (cache != null)
                        {
                            fromCache = true;
                            byte[] buffer = (byte[])cache;
                            memoryStream.Write(buffer, 0, buffer.Length);
                        }
                    }

                    if (!fromCache)
                    {
                        int             width           = request.GetQueryStringValue <int>("w", 0);
                        int             height          = request.GetQueryStringValue <int>("h", 0);
                        GraphicsQuality graphicsQuality = (GraphicsQuality)request.GetQueryStringValue <int>("rq", 2);
                        bool            maintainPalette = request.GetQueryStringValue <bool>("mp", false);
                        bool            clip            = request.GetQueryStringValue <bool>("cl", false);

                        using (Image originalImage = imageRetriever.GetImage())
                            using (Image resizedBitmap = (clip) ? originalImage.Clip(width, height, graphicsQuality, maintainPalette)
                                                            : originalImage.Resize(width, height, graphicsQuality, maintainPalette)) {
                                if (!resizedBitmap.HasIndexedPixelFormat())
                                {
                                    string copyrightText = request.GetQueryStringValue <string>("ct", null);
                                    if (!string.IsNullOrEmpty(copyrightText))
                                    {
                                        int copyrightFontSize = request.GetQueryStringValue <int>("cts", 0);
                                        resizedBitmap.AddCopyrightText(copyrightText, copyrightFontSize);
                                    }

                                    if (request.GetQueryStringValue("g", false))
                                    {
                                        resizedBitmap.ApplyGrayscaleColorMatrix();
                                    }

                                    if (request.GetQueryStringValue("n", false))
                                    {
                                        resizedBitmap.ApplyNegativeColorMatrix();
                                    }

                                    if (request.GetQueryStringValue("s", false))
                                    {
                                        resizedBitmap.ApplySepiaColorMatrix();
                                    }

                                    float brightness = request.GetQueryStringValue <float>("b", 0F);
                                    if (brightness != 0)
                                    {
                                        resizedBitmap.SetBrightness(brightness);
                                    }

                                    float contrast = request.GetQueryStringValue <float>("c", 0F);
                                    if (contrast != 0)
                                    {
                                        resizedBitmap.SetContrast(contrast);
                                    }
                                }

                                ImageFormat imageFormat   = GetImageFormatByExtension(extension);
                                long        outputQuality = request.GetQueryStringValue <long>("oq", 75L);

                                if (QuantizeableExtension(extension) && request.GetQueryStringValue <bool>("q", false))
                                {
                                    using (Image quantizedBitmap = resizedBitmap.OctreeQuantize()) {
                                        quantizedBitmap.SaveToMemoryStream(memoryStream, imageFormat, outputQuality);
                                    }
                                }
                                else
                                {
                                    resizedBitmap.SaveToMemoryStream(memoryStream, imageFormat, outputQuality);
                                }
                            }
                    }

                    memoryStream.Capacity = (int)memoryStream.Position;
                    if (memoryStream.Capacity > 0)
                    {
                        response.Cache.SetExpires(DateTime.Now.AddMinutes(browserCacheExpirationMinutes));
                        response.Cache.SetLastModified(imageRetriever.GetLastModifiedDate());

                        memoryStream.WriteTo(context.Response.OutputStream);

                        if (cacheOutput && !fromCache)
                        {
                            context.Cache[hash] = memoryStream.ToArray();
                        }
                    }
                }
            }
            catch (FileNotFoundException) {
                context.Response.StatusCode = (int)HttpStatusCode.NotFound;
            }
            catch (HttpException httpException) {
                context.Response.StatusCode = httpException.GetHttpCode();
            }
            finally {
                context.Response.Flush();
                context.Response.End();
            }
        }
Exemplo n.º 4
0
        private void ProcessFullRequest(HttpResponse response)
        {
            using (MemoryStream memoryStream = new MemoryStream()) {
                ImageTransformer imageTransformer = new ImageTransformer();
                imageTransformer.GraphicsQuality = ImageSettings.GraphicsQuality;
                imageTransformer.Copyright       = ImageSettings.Copyright;
                imageTransformer.CopyrightSize   = ImageSettings.CopyrightSize;
                imageTransformer.MaxWidth        = ImageSettings.MaxWidth;
                imageTransformer.MaxHeight       = ImageSettings.MaxHeight;
                imageTransformer.Grayscale       = ImageSettings.Grayscale;
                imageTransformer.Negative        = ImageSettings.Negative;
                imageTransformer.Sepia           = ImageSettings.Sepia;
                imageTransformer.Clip            = ImageSettings.Clip;
                imageTransformer.Quantize        = ImageSettings.Quantize;
                imageTransformer.MaintainPalette = ImageSettings.MaintainPalette;
                imageTransformer.Brightness      = ImageSettings.Brightness;
                imageTransformer.Contrast        = ImageSettings.Contrast;
                imageTransformer.Opacity         = ImageSettings.Opacity;

                string customTransform = ImageSettings.CustomTransform;
                if (!string.IsNullOrEmpty(customTransform))
                {
                    string         customTransformClassName = config.GetImageTransformClassName(customTransform);
                    ImageTransform customTransformClass     = ImageTransformFactory.Create(customTransformClassName);

                    ICustomDataConsumer customTransFormClassAsCustomDataConsumer = customTransformClass as ICustomDataConsumer;
                    if (customTransFormClassAsCustomDataConsumer != null)
                    {
                        customTransFormClassAsCustomDataConsumer.SetCustomData(ImageSettings.CustomData);
                    }

                    imageTransformer.CustomTransforms.Add(customTransformClass);
                }

                ImageRetriever.EnsureImage();
                using (Image originalImage = ImageRetriever.GetImage())
                    using (Image resizedBitmap = imageTransformer.Transform(originalImage)) {
                        long        outputQuality = ImageSettings.OutputQuality;
                        ImageFormat imageFormat   = ImageMetadata.ImageFormat;

                        resizedBitmap.SaveToMemoryStream(memoryStream, imageFormat, outputQuality);
                    }

                memoryStream.Capacity = (int)memoryStream.Position;



                if (memoryStream.Capacity > 0)
                {
                    if (ImageSettings.ServerCacheTimeout > 0)
                    {
                        ImageCacheBroker.AddImageBytes(memoryStream.ToArray());
                    }

                    response.ContentType = ImageMetadata.ContentType;
                    response.AppendHeader("Content-Disposition", string.Concat("inline; filename=\"", ImageMetadata.SaveName, "\""));
                    response.AppendHeader("Content-Length", memoryStream.Capacity.ToString(CultureInfo.InvariantCulture));
                    response.Cache.SetCacheability(HttpCacheability.Public);
                    response.Cache.SetAllowResponseInBrowserHistory(true);
                    response.Cache.SetLastModified(ImageMetadata.LastModifiedDate);
                    response.Cache.SetValidUntilExpires(true);
                    response.Cache.SetExpires(DateTime.UtcNow.AddMinutes(ImageSettings.ClientCacheTimeout));

                    memoryStream.WriteTo(response.OutputStream);
                }
            }
        }