Esempio n. 1
0
        public static void Main(string[] args)
        {
            const string InputImages  = @"..\..\..\ImageProcessor.UnitTests\Images\";
            const string OutputImages = @"..\..\images\output";

            string root    = new Uri(System.Reflection.Assembly.GetExecutingAssembly().CodeBase).LocalPath;
            string inPath  = Path.GetFullPath(Path.Combine(Path.GetDirectoryName(root), InputImages));
            string outPath = Path.GetFullPath(Path.Combine(Path.GetDirectoryName(root), OutputImages));

            DirectoryInfo          di    = new DirectoryInfo(inPath);
            IEnumerable <FileInfo> files = GetFilesByExtensions(di, ".jpg", ".jpeg", ".jfif", ".gif", ".bmp", ".png", ".tif");

            foreach (FileInfo fileInfo in files)
            {
                // Start timing.
                byte[] photoBytes = File.ReadAllBytes(fileInfo.FullName);
                Console.WriteLine("Processing: " + fileInfo.Name);

                Stopwatch stopwatch = new Stopwatch();
                stopwatch.Start();

                using (MemoryStream inStream = new MemoryStream(photoBytes))
                    using (ImageFactory imageFactory = new ImageFactory(true, true)
                    {
                        AnimationProcessMode = AnimationProcessMode.All
                    })
                    {
                        Size size = new Size(50, 0);

                        ResizeLayer layer = new ResizeLayer(size);
                        try
                        {
                            imageFactory.Load(inStream)
                            .BitDepth(1)
                            //.Resize(size)
                            //.Format(new GifFormat())
                            //.Resolution(400, 400)
                            //.ReplaceColor(Color.LightGray, Color.Yellow, 10)
                            .Save(Path.GetFullPath(Path.Combine(outPath, fileInfo.Name)));
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(ex.Message);
                        }

                        stopwatch.Stop();

                        // trans.gif says it's (0, 0, 0, 0) but the image saves as black.
                        // Color first = ((Bitmap)imageFactory.Image).GetPixel(0, 0);
                    }

                // Report back.
                long  peakWorkingSet64 = Process.GetCurrentProcess().PeakWorkingSet64;
                float mB = peakWorkingSet64 / (float)1024 / 1024;

                Console.WriteLine(@"Completed {0} in {1:s\.fff} secs {2}Peak memory usage was {3} bytes or {4} Mb.", fileInfo.Name, stopwatch.Elapsed, Environment.NewLine, peakWorkingSet64.ToString("#,#"), mB);
            }

            Console.ReadLine();
        }
Esempio n. 2
0
        public void TestResizeRegex()
        {
            Dictionary <string, ResizeLayer> data = new Dictionary <string, ResizeLayer>
            {
                {
                    "width=300", new ResizeLayer(new Size(300, 0))
                },
                {
                    "height=300", new ResizeLayer(new Size(0, 300))
                },
                {
                    "height=300&mode=crop", new ResizeLayer(new Size(0, 300), ResizeMode.Crop)
                },
                {
                    "width=300&mode=crop", new ResizeLayer(new Size(300, 0), ResizeMode.Crop)
                },
                {
                    "width=600&heightratio=0.416", new ResizeLayer(new Size(600, 250))
                },
                {
                    "width=600&height=250&mode=max", new ResizeLayer(new Size(600, 250), ResizeMode.Max)
                }
            };

            Processors.Resize resize = new Processors.Resize();
            foreach (KeyValuePair <string, ResizeLayer> item in data)
            {
                resize.MatchRegexIndex(item.Key);
                ResizeLayer result = resize.Processor.DynamicParameter;
                Assert.AreEqual(item.Value, result);
            }
        }
        private void Recompress(string sourceName, string destName, int width, int height, int quality)
        {
            ISupportedImageFormat format = new JpegFormat {
                Quality = quality
            };
            var size = new Size(width, height);
            var rl   = new ResizeLayer(size, ResizeMode.Crop);

            using (FileStream src = File.OpenRead(Path.Combine(_baseDir, sourceName)))
            {
                string destPath = Path.Combine(_baseDir, destName);
                if (File.Exists(destPath))
                {
                    File.Delete(destPath);
                }
                using (FileStream dest = File.Create(destPath))
                {
                    using (var factory = new ImageFactory())
                    {
                        factory
                        .Load(src)
                        .Resize(rl)
                        .Format(format)
                        .Save(dest);
                    }
                }
            }
        }
        public HttpResponseMessage GetThumbnail(string imagePath, int width)
        {
            if (false == string.IsNullOrWhiteSpace(imagePath) && imagePath.IndexOf("{{") < 0)
            {
                var image = Image.FromFile(System.Web.Hosting.HostingEnvironment.MapPath(imagePath));

                MemoryStream outStream = new MemoryStream();

                byte[] photoBytes            = File.ReadAllBytes(System.Web.Hosting.HostingEnvironment.MapPath(imagePath)); // change imagePath with a valid image path
                ISupportedImageFormat format = new JpegFormat {
                    Quality = 70
                };                                                              // convert to jpg

                var inStream = new MemoryStream(photoBytes);

                var imageFactory = new ImageFactory(preserveExifData: true);

                Size size = ResizeKeepAspect(image.Size, width, width);

                ResizeLayer resizeLayer = new ResizeLayer(size, ResizeMode.Max);
                imageFactory.Load(inStream)
                .Resize(resizeLayer)
                .Format(format)
                .Save(outStream);

                HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
                response.Content = new StreamContent(outStream);
                response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("image/png");
                return(response);
            }
            else
            {
                return(null);
            }
        }
Esempio n. 5
0
        protected byte[] ApplyResize(byte[] pictureBinary, int targetSize, Size originalSize = default(Size))
        {
            var resizeLayer = default(ResizeLayer);

            if (originalSize != default(Size))
            {
                resizeLayer = new ResizeLayer(CalculateDimensions(originalSize, targetSize), ResizeMode.Max);
            }
            else
            {
                //ValidatePicture() only
                resizeLayer = new ResizeLayer(new Size(targetSize, targetSize), ResizeMode.Max);
            }

            using (MemoryStream inStream = new MemoryStream(pictureBinary))
            {
                using (MemoryStream outStream = new MemoryStream())
                {
                    using (ImageFactory imageFactory = new ImageFactory())
                    {
                        imageFactory.Load(inStream)
                        .Resize(resizeLayer)
                        .Quality(_mediaSettings.DefaultImageQuality)
                        .Save(outStream);
                        inStream.Dispose();
                        imageFactory.Dispose();
                        return(outStream.ToArray());
                    }
                }
            }
        }
Esempio n. 6
0
        public BlobStorage(BlobSettings appSettings)
        {
            try
            {
                if (appSettings.ImageSize != null)
                {
                    ResizeLayer = new ResizeLayer(appSettings.ImageSize, ResizeMode.Min);
                }

                UploadThumbnail = appSettings.UploadThumbnail;

                StorageAccountName      = appSettings.StorageAccountName;
                StorageAccountAccessKey = appSettings.StorageAccountAccessKey;

                // Create a blob client and retrieve reference to images container
                BlobClient = StorageAccount.CreateCloudBlobClient();
                Container  = BlobClient.GetContainerReference(appSettings.ContainerName);

                // Create the "images" container if it doesn't already exist.
                if (Container.CreateIfNotExists())
                {
                    // Enable public access on the newly created "images" container
                    Container.SetPermissions(
                        new BlobContainerPermissions
                    {
                        PublicAccess =
                            BlobContainerPublicAccessType.Blob
                    });
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
            }
        }
Esempio n. 7
0
        static void Main(string[] args)
        {
            // Create Destination folder if it doesn't exist
            Directory.CreateDirectory(PhotoDestination);

            using (ImageFactory imageFactory = new ImageFactory(preserveExifData: true))
            {
                var resizelayer = new ResizeLayer(new System.Drawing.Size(1500, 1500), ResizeMode.Min);

                string[] files = Directory.GetFiles(PhotoSource);

                int i = 1;

                foreach (var path in files)
                {
                    var filename = Path.GetFileName(path);

                    imageFactory.Load(Path.Combine(PhotoSource, filename))
                    .Resize(resizelayer)
                    .Quality(90)
                    .Save(Path.Combine(PhotoDestination, filename));

                    Console.WriteLine(i++);
                }
            }
        }
Esempio n. 8
0
        public static void ToWebP(Image inputImage, string outputImage, Size?size = null)
        {
            if (inputImage == null)
            {
                return;
            }

            size = size ?? new Size(inputImage.Width, inputImage.Height);

            // Format is automatically detected though can be changed.
            ISupportedImageFormat format = new WebPFormat();

            using (FileStream outStream = new FileStream(outputImage, FileMode.Create))
            {
                // Initialize the ImageFactory using the overload to preserve EXIF metadata.
                using (ImageFactory imageFactory = new ImageFactory(true))
                {
                    var resizeLayer = new ResizeLayer((Size)size, ResizeMode.Stretch);

                    // Load, resize, set the format and quality and save an image.
                    imageFactory.Load(inputImage)
                    .Format(format)
                    .Resize(resizeLayer)
                    .Save(outStream);
                }
                // Do something with the stream.
            }
        }
Esempio n. 9
0
        public static byte[] GetRawImageAutoRotatedAndResized(
            string itemFilePath, int width, int height, bool shouldPad)
        {
            try
            {
                bool requiresRotation = ImageRequiresRotation(itemFilePath);

                using (var imageFactory = new ImageFactory())
                {
                    var resizeLayer = new ResizeLayer(new Size(width, height), shouldPad ? ResizeMode.Pad : ResizeMode.Max);

                    imageFactory.Load(itemFilePath);

                    if (requiresRotation)
                    {
                        imageFactory.AutoRotate();
                    }

                    imageFactory.Resize(resizeLayer);

                    using (var ms = new MemoryStream())
                    {
                        imageFactory.Save(ms);
                        return(ms.ToArray());
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Logger.Error(ex, $"Could not auto-rotate and resize image {itemFilePath}");
            }

            return(null);
        }
        private void SavingMedia(IMediaService sender, SaveEventArgs <IMedia> e)
        {
            MediaFileSystem      mediaFileSystem = FileSystemProviderManager.Current.GetFileSystemProvider <MediaFileSystem>();
            IContentSection      contentSection  = UmbracoConfig.For.UmbracoSettings().Content;
            IEnumerable <string> supportedTypes  = contentSection.ImageFileTypes.ToList();

            foreach (var entity in e.SavedEntities)
            {
                if (!entity.HasProperty("umbracoFile"))
                {
                    continue;
                }

                var path      = entity.GetValue <string>("umbracoFile");
                var extension = Path.GetExtension(path)?.Substring(1);

                if (!supportedTypes.InvariantContains(extension))
                {
                    continue;
                }

                var fullPath = mediaFileSystem.GetFullPath(path);
                using (ImageFactory imageFactory = new ImageFactory(true))
                {
                    ResizeLayer layer = new ResizeLayer(new Size(1920, 0), ResizeMode.Max)
                    {
                        Upscale = false
                    };

                    imageFactory.Load(fullPath)
                    .Resize(layer)
                    .Save(fullPath);
                }
            }
        }
Esempio n. 11
0
        public int MatchRegexIndex(string queryString)
        {
            this.SortOrder = int.MaxValue;
            Match match = this.RegexPattern.Match(queryString);

            if (match.Success)
            {
                this.SortOrder = match.Index;
                NameValueCollection queryCollection = HttpUtility.ParseQueryString(queryString);

                Size size = this.ParseSize(queryCollection);

                ResizeLayer resizeLayer = new ResizeLayer(size)
                {
                    ResizeMode        = ResizeMode.Max,
                    AnchorPosition    = AnchorPosition.Center,
                    Upscale           = false,
                    CenterCoordinates = new float[] { }
                };

                this.Processor.DynamicParameter = resizeLayer;

                string restrictions;
                this.Processor.Settings.TryGetValue("RestrictTo", out restrictions);
                ((ImageProcessor.Processors.Resize) this.Processor).RestrictedSizes = this.ParseRestrictions(
                    restrictions);
            }

            return(this.SortOrder);
        }
Esempio n. 12
0
        public Task <Stream> TransformImage(Stream image, ImageDisParameters param)
        {
            var newImage = new MemoryStream();

            using (var imageFactory = new ImageFactory(preserveExifData: false))
            {
                var chain = imageFactory.Load(image);

                if (param.Has("w") || param.Has("h"))
                {
                    var resizeLayer = new ResizeLayer(new Size(param.Get <int>("w"), param.Get <int>("h")));
                    resizeLayer.ResizeMode     = ResizeMode.Max;
                    resizeLayer.AnchorPosition = AnchorPosition.Center;

                    if (param.Has("pad") && param.Get <bool>("pad"))
                    {
                        resizeLayer.ResizeMode = ResizeMode.Pad;
                    }

                    chain.Resize(resizeLayer);
                }

                chain.Save(newImage);
            }

            return(Task.FromResult <Stream>(newImage));
        }
Esempio n. 13
0
        public void ResizeImage(object obj)
        {
            string str = (obj is string) ? obj as string : string.Empty;

            ImageProcessor.Imaging.ResizeMode mode;

            if (str == "max")
            {
                mode = ImageProcessor.Imaging.ResizeMode.Max;
            }
            else
            {
                mode = ImageProcessor.Imaging.ResizeMode.Stretch;
            }

            using (Process = new MemoryStream())
            {
                var size = new System.Drawing.Size(W, H);
                Rec = new Rectangle(Rec.X, Rec.Y, size.Width, size.Height);
                ResizeLayer resizeLayer = new ResizeLayer(size, mode, AnchorPosition.Center, true, null, null, null, null);

                using (var imageFactory = new ImageFactory(preserveExifData: true))
                {
                    imageFactory.Load(Input)
                    .Resize(resizeLayer)
                    .Save(Process);
                }

                SaveProcess();
            }
        }
        public void TestResizeRegex()
        {
            Dictionary <string, ResizeLayer> data = new Dictionary <string, ResizeLayer>
            {
                { "width=300", new ResizeLayer(new Size(300, 0)) },
                { "height=300", new ResizeLayer(new Size(0, 300)) },
                { "height=300.6", new ResizeLayer(new Size(0, 301)) }, // Round size units
                { "height=300&mode=crop", new ResizeLayer(new Size(0, 300), ResizeMode.Crop) },
                { "width=300&mode=crop", new ResizeLayer(new Size(300, 0), ResizeMode.Crop) },
                { "width=300.2&mode=crop", new ResizeLayer(new Size(300, 0), ResizeMode.Crop) }, // Round size units
                { "width=600&heightratio=0.416", new ResizeLayer(new Size(600, 250)) },
                { "width=600&height=250&mode=max", new ResizeLayer(new Size(600, 250), ResizeMode.Max) },
                { "width=600&height=250&center=1,0.5", new ResizeLayer(new Size(600, 250), centerCoordinates: new [] { 1f, 0.5f }) }, // Center coordinates (Y,X)
                { "width=600&height=250&center=0.5,0.25", new ResizeLayer(new Size(600, 250))
                  {
                      Center = new PointF(0.25f, 0.5f)
                  } },                                                                      // Center coordinates (Y,X) to PointF
                { "width=600&height=250&center=0.5", new ResizeLayer(new Size(600, 250)) }, // Invalid center coordinates should not result in 0,0
                { "width=600&height=250&center=y,x", new ResizeLayer(new Size(600, 250)) } // Invalid center coordinates should not result in 0,0
            };

            Processors.Resize resize = new Processors.Resize();
            foreach (KeyValuePair <string, ResizeLayer> item in data)
            {
                resize.MatchRegexIndex(item.Key);
                ResizeLayer result = resize.Processor.DynamicParameter;
                Assert.AreEqual(item.Value, result);
            }
        }
Esempio n. 15
0
        public void ResizeImg(string file)
        {
            var replace = true;

            if (file == "")
            {
                file = @"D:\img.jpeg";
            }
            var outfile = file;

            if (!replace)
            {
                outfile = file.Replace(".jpeg", "_out" + DateTime.Now.ToString("MMddHHmmss") + ".jpeg");
            }

            var minDimMax = 256;

            byte[] photoBytes = File.ReadAllBytes(file);

            using (MemoryStream inStream = new MemoryStream(photoBytes))
            {
                using (var img = System.Drawing.Image.FromStream(inStream))
                {
                    var w = img.Width;
                    var h = img.Height;
                    //if (w > minDimMax && h > minDimMax)
                    //{
                    // Format is automatically detected though can be changed.
                    ISupportedImageFormat format = new JpegFormat {
                        Quality = 90
                    };

                    Size size1 = new Size(minDimMax, minDimMax * 10);
                    Size size2 = new Size(minDimMax * 10, minDimMax);

                    var         resize1 = new ResizeLayer(size1, ResizeMode.Max);
                    var         resize2 = new ResizeLayer(size2, ResizeMode.Max);
                    ResizeLayer layer   = w < h ? resize1 : resize2;
                    using (MemoryStream outStream = new MemoryStream())
                    {
                        // Initialize the ImageFactory using the overload to preserve EXIF metadata.
                        using (ImageFactory imageFactory = new ImageFactory(preserveExifData: true))
                        {
                            // Load, resize, set the format and quality and save an image.
                            imageFactory.Load(inStream)
                            .Resize(layer)
                            .Format(format)
                            .Save(outfile);
                        }
                    }
                    //}
                    //else if (!replace)
                    //{
                    //    File.Copy(file, outfile);
                    //}
                }
            }
        }
Esempio n. 16
0
        /// <summary>
        /// Processes the image.
        /// </summary>
        /// <param name="factory">
        /// The current instance of the <see cref="T:ImageProcessor.ImageFactory"/> class containing
        /// the image to process.
        /// </param>
        /// <returns>
        /// The processed image from the current instance of the <see cref="T:ImageProcessor.ImageFactory"/> class.
        /// </returns>
        public Image ProcessImage(ImageFactory factory)
        {
            Bitmap newImage = null;
            Image  image    = factory.Image;

            try
            {
                ResizeLayer resizeLayer = this.DynamicParameter;

                // Augment the layer with the extra information.
                resizeLayer.RestrictedSizes = this.RestrictedSizes;
                Size maxSize = new Size();

                int maxWidth;
                int maxHeight;
                int.TryParse(this.Settings["MaxWidth"], NumberStyles.Any, CultureInfo.InvariantCulture, out maxWidth);
                int.TryParse(this.Settings["MaxHeight"], NumberStyles.Any, CultureInfo.InvariantCulture, out maxHeight);

                maxSize.Width  = maxWidth;
                maxSize.Height = maxHeight;

                resizeLayer.MaxSize = maxSize;

                Resizer resizer = new Resizer(resizeLayer)
                {
                    ImageFormat = factory.CurrentImageFormat, AnimationProcessMode = factory.AnimationProcessMode
                };
                newImage = resizer.ResizeImage(image, factory.FixGamma);

                // Check that the original image has not been returned.
                if (newImage != image)
                {
                    // Reassign the image.
                    image.Dispose();
                    image = newImage;

                    if (factory.PreserveExifData && factory.ExifPropertyItems.Any())
                    {
                        // Set the width EXIF data.
                        factory.SetPropertyItem(ExifPropertyTag.ImageWidth, (ushort)image.Width);

                        // Set the height EXIF data.
                        factory.SetPropertyItem(ExifPropertyTag.ImageHeight, (ushort)image.Height);
                    }
                }
            }
            catch (Exception ex)
            {
                if (newImage != null)
                {
                    newImage.Dispose();
                }

                throw new ImageProcessingException("Error processing image with " + this.GetType().Name, ex);
            }

            return(image);
        }
        public static Image Resize(this Image image, Size size)
        {
            using var factory            = new ImageFactory(preserveExifData: true);
            using var resizedImageStream = new MemoryStream();
            var resizeLayer = new ResizeLayer(size: size, resizeMode: ResizeMode.Stretch);

            factory.Load(image).Resize(resizeLayer).Save(resizedImageStream);
            return(Image.FromStream(resizedImageStream));
        }
Esempio n. 18
0
        /// <summary>
        /// The position in the original string where the first character of the captured substring was found.
        /// </summary>
        /// <param name="queryString">The query string to search.</param>
        /// <returns>
        /// The zero-based starting position in the original string where the captured substring was found.
        /// </returns>
        public int MatchRegexIndex(string queryString)
        {
            int index = 0;

            // Set the sort order to max to allow filtering.
            this.SortOrder = int.MaxValue;

            // First merge the matches so we can parse .
            StringBuilder stringBuilder = new StringBuilder();

            foreach (Match match in this.RegexPattern.Matches(queryString))
            {
                if (match.Success)
                {
                    // We don't want any resize carve or percentile crops requests to interfere.
                    // TODO: This is hacky and awful and should go.
                    if (match.Value.ToUpperInvariant().Contains("CARVE") || match.Value.ToUpperInvariant().Contains("PERCENT"))
                    {
                        break;
                    }

                    if (index == 0)
                    {
                        // Set the index on the first instance only.
                        this.SortOrder = match.Index;
                        stringBuilder.Append(queryString);
                    }

                    index += 1;
                }
            }

            if (this.SortOrder < int.MaxValue)
            {
                // Match syntax
                string toParse = stringBuilder.ToString();

                Size        size        = this.ParseSize(toParse);
                ResizeLayer resizeLayer = new ResizeLayer(size)
                {
                    ResizeMode        = this.ParseMode(toParse),
                    AnchorPosition    = this.ParsePosition(toParse),
                    Upscale           = !UpscaleRegex.IsMatch(toParse),
                    CenterCoordinates = this.ParseCoordinates(toParse),
                };

                this.Processor.DynamicParameter = resizeLayer;

                // Correctly parse any restrictions.
                string restrictions;
                this.Processor.Settings.TryGetValue("RestrictTo", out restrictions);
                ((ImageProcessor.Processors.Resize) this.Processor).RestrictedSizes = this.ParseRestrictions(
                    restrictions);
            }

            return(this.SortOrder);
        }
Esempio n. 19
0
        public HttpResponseMessage GetThumbnail(string imagePath = "", string width = "150")
        {
            width = width ?? "150";
            var imageWidth = 0;

            Int32.TryParse(width, out imageWidth);

            if (!string.IsNullOrWhiteSpace(imagePath) && imagePath.IndexOf("{{") < 0)
            {
                if (File.Exists(System.Web.Hosting.HostingEnvironment.MapPath(imagePath)))
                {
                    FileInfo fileInfo = new FileInfo(System.Web.Hosting.HostingEnvironment.MapPath(imagePath));

                    if (fileInfo.Extension.ToLower() == ".jpg" || fileInfo.Extension.ToLower() == ".gif" || fileInfo.Extension.ToLower() == ".png")
                    {
                        using (var image = Image.FromFile(System.Web.Hosting.HostingEnvironment.MapPath(imagePath)))
                        {
                            MemoryStream outStream = new MemoryStream();

                            byte[] photoBytes            = File.ReadAllBytes(System.Web.Hosting.HostingEnvironment.MapPath(imagePath)); // change imagePath with a valid image path
                            ISupportedImageFormat format = new JpegFormat {
                                Quality = 70
                            };                                                              // convert to jpg

                            var inStream = new MemoryStream(photoBytes);

                            var imageFactory = new ImageFactory(preserveExifData: true);

                            Size size = ResizeKeepAspect(image.Size, imageWidth, imageWidth);

                            ResizeLayer resizeLayer = new ResizeLayer(size, ResizeMode.Max);
                            imageFactory.Load(inStream)
                            .Resize(resizeLayer)
                            .Format(format)
                            .Save(outStream);
                            HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
                            response.Content = new StreamContent(outStream);
                            response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("image/png");
                            return(response);
                        }
                    }
                    else
                    {
                        return(new HttpResponseMessage(HttpStatusCode.OK));
                    }
                }
                else
                {
                    return(new HttpResponseMessage(HttpStatusCode.OK));
                }
            }
            else
            {
                return(new HttpResponseMessage(HttpStatusCode.OK));
            }
        }
Esempio n. 20
0
        public void Normalize()
        {
            ISupportedImageFormat format = new JpegFormat {
                Quality = 70
            };
            ResizeLayer resizeLayer = new ResizeLayer(new System.Drawing.Size(1024, 768), resizeMode: ResizeMode.Min);

            Image.Resize(resizeLayer)
            .Format(format);
        }
Esempio n. 21
0
        public ActionResult ResizeImage(string size, string fileId, string fileName)
        {
            try
            {
                if (!string.IsNullOrEmpty(Request.Headers["If-Modified-Since"]))
                {
                    Response.StatusCode        = 304;
                    Response.StatusDescription = "Not Modified";
                    Response.AddHeader("Content-Length", "0");
                    return(Content(string.Empty));
                }

                #region Temp Path
                var tempPath = Server.MapPath("~/Temp/Thumb/resize");
                if (!Directory.Exists(tempPath))
                {
                    Directory.CreateDirectory(tempPath);
                }
                var filePath = $"{tempPath}\\{size}-{fileId}{Path.GetExtension(fileName)}";
                if (System.IO.File.Exists(filePath))
                {
                    byte[] filedata    = System.IO.File.ReadAllBytes(filePath);
                    string contentType = MimeMapping.GetMimeMapping(filePath);

                    return(File(filedata, contentType));
                }
                #endregion

                var sizes = size.Split('x').Select(x => int.Parse(x)).ToArray();
                var file  = AsefianFileContextHelper.GetFile(fileId, fileName);

                MemoryStream          outStream = new MemoryStream();
                ISupportedImageFormat format    = new JpegFormat {
                    Quality = 70
                };

                using (ImageFactory imageFactory = new ImageFactory(preserveExifData: false))
                {
                    var resizeLayer = new ResizeLayer(new Size(sizes[0], sizes[1]), ResizeMode.Min);

                    imageFactory.Load(file.Data)
                    .Resize(resizeLayer)
                    .Format(format)
                    .Save(filePath)
                    .Save(outStream);

                    return(File(outStream, MimeMapping.GetMimeMapping(fileName)));
                }
            }
            catch (Exception ex)
            {
                ServerError(ex);
                return(HttpNotFound());
            }
        }
Esempio n. 22
0
        private void Resize(ImageFactory imageFactory, ProcessingParameters parameters)
        {
            if (parameters.ScaleX == 1 && parameters.ScaleY == 1)
            {
                return;
            }
            var size        = new Size((int)(imageFactory.Image.Width * parameters.ScaleX), (int)(imageFactory.Image.Height * parameters.ScaleY));
            var resizeLayer = new ResizeLayer(size, ResizeMode.Stretch);

            imageFactory.Resize(resizeLayer);
        }
        /// <summary>
        /// Constrains the current image, resizing it to fit within the given dimensions whilst keeping its aspect ratio.
        /// </summary>
        /// <param name="size">
        /// The <see cref="T:System.Drawing.Size"/> containing the maximum width and height to set the image to.
        /// </param>
        /// <returns>
        /// The current instance of the <see cref="T:ImageProcessor.ImageFactory"/> class.
        /// </returns>
        public ImageFactory Constrain(Size size)
        {
            if (this.ShouldProcess)
            {
                ResizeLayer layer = new ResizeLayer(size, ResizeMode.Max);

                return(this.Resize(layer));
            }

            return(this);
        }
Esempio n. 24
0
        public void TestResizeRegex()
        {
            const string Querystring = "width=300";
            ResizeLayer  expected    = new ResizeLayer(new Size(300, 0));

            Resize resize = new Resize();

            resize.MatchRegexIndex(Querystring);
            ResizeLayer actual = resize.DynamicParameter;

            Assert.AreEqual(expected, actual);
        }
        /// <summary>
        /// Resizes the current image to the given dimensions.
        /// </summary>
        /// <param name="size">
        /// The <see cref="T:System.Drawing.Size"/> containing the width and height to set the image to.
        /// </param>
        /// <returns>
        /// The current instance of the <see cref="T:ImageProcessor.ImageFactory"/> class.
        /// </returns>
        public ImageFactory Resize(Size size)
        {
            if (this.ShouldProcess)
            {
                int width  = size.Width;
                int height = size.Height;

                ResizeLayer resizeLayer = new ResizeLayer(new Size(width, height));
                return(this.Resize(resizeLayer));
            }

            return(this);
        }
Esempio n. 26
0
        /// <summary>
        /// 上传图片
        /// </summary>
        /// <returns></returns>
        public async Task <IHttpActionResult> Post()
        {
            try
            {
                string fileName        = Guid.NewGuid().ToString();
                string fileOrginalFile = HttpContext.Current.Server.MapPath("~/MyUpload/" + Guid.NewGuid().ToString() + ".jpg");


                ;
                string fileResized800Name = HttpContext.Current.Server.MapPath("~/MyUpload/" + Guid.NewGuid().ToString() + ".jpg");

                System.Drawing.Bitmap image = new System.Drawing.Bitmap(HttpContext.Current.Request.InputStream);

                image.Save(fileOrginalFile);


                using (var imageFactory = new ImageFactory(preserveExifData: true))
                {
                    System.Drawing.Size size   = new System.Drawing.Size(800, 1600);
                    ResizeLayer         resize = new ResizeLayer(size, ResizeMode.Max);
                    imageFactory.Load(fileOrginalFile).Resize(resize).Save(fileResized800Name);
                }
                BlobHelper blob        = new BlobHelper(BlobString.Portrait);
                string     contentType = "image/jpeg";

                await blob.UploadFile(fileResized800Name, fileName, contentType);

                //删除文件
                File.Delete(fileOrginalFile);

                File.Delete(fileResized800Name);



                return(Json(new
                {
                    Code = 10000,
                    Detail = "http://hdy.awblob.com/portrait/" + fileName
                }));
            }

            catch (Exception ex)
            {
                return(Json(new
                {
                    Code = 10,
                    Message = "上传失败"
                }));
            }
        }
Esempio n. 27
0
        public void ResizeIsApplied()
        {
            Size        stretchedSize = new Size(400, 400);
            ResizeLayer stretchLayer  = new ResizeLayer(stretchedSize, ResizeMode.Stretch);

            Size paddedSize = new Size(700, 700);
            // ReSharper disable once RedundantArgumentDefaultValue
            ResizeLayer paddedLayer = new ResizeLayer(paddedSize, ResizeMode.Pad);

            Size        cropSize  = new Size(600, 450);
            ResizeLayer cropLayer = new ResizeLayer(cropSize, ResizeMode.Crop);

            Size        minSize  = new Size(300, 300);
            ResizeLayer minLayer = new ResizeLayer(minSize, ResizeMode.Min);

            int i = 0;

            foreach (ImageFactory imageFactory in this.ListInputImages())
            {
                Image original = (Image)imageFactory.Image.Clone();

                // First stretch
                imageFactory.Format(new JpegFormat()).Resize(stretchLayer);
                AssertionHelpers.AssertImagesAreDifferent(original, imageFactory.Image, "because the resize operation should have been applied on {0}", imageFactory.ImagePath);

                Assert.AreEqual(imageFactory.Image.Size, stretchedSize);
                imageFactory.Save("./output/resize-stretch-" + i + ".jpg");

                // Check we padd correctly.
                imageFactory.Resize(paddedLayer);
                Assert.AreEqual(imageFactory.Image.Size, paddedSize);
                imageFactory.Save("./output/resize-padd-" + i + ".jpg");

                // Check we crop correctly.
                imageFactory.Resize(cropLayer);
                Assert.AreEqual(imageFactory.Image.Size, cropSize);
                imageFactory.Save("./output/resize-crop-" + i + ".jpg");

                // Check we min correctly using the shortest size.
                imageFactory.Resize(minLayer);
                Assert.AreEqual(imageFactory.Image.Size, new Size(400, 300));
                imageFactory.Save("./output/resize-crop-" + i + ".jpg");

                imageFactory.Reset();
                AssertionHelpers.AssertImagesAreIdentical(original, imageFactory.Image, "because the image should be reset");

                imageFactory.Format(new JpegFormat()).Save("./output/resize-" + i + ".jpg");
            }
        }
Esempio n. 28
0
        private bool Resize(string sourceFileName, string destinationFileName)
        {
            // The wolf made a change
            // So I'm going to try and push this back

            if (!File.Exists(destinationFileName))
            {
                float width  = 0;
                float height = 0;

                using (FileStream file = new FileStream(sourceFileName, FileMode.Open, FileAccess.Read))
                {
                    using (Image tif = Image.FromStream(file, false, false))
                    {
                        width  = tif.Width / 2;
                        height = tif.Height / 2;

                        while (Math.Min(width, height) > 1500)
                        {
                            width  = width / 2;
                            height = height / 2;
                        }
                    }
                }

                // Read a file and resize it.
                byte[] photoBytes = File.ReadAllBytes(sourceFileName);
                int    quality    = 70;

                JpegFormat format = new JpegFormat();

                Size size = new Size((int)width, (int)height);

                using (MemoryStream inStream = new MemoryStream(photoBytes))
                {
                    using (ImageFactory imageFactory = new ImageFactory(true))
                    {
                        ResizeLayer resizeLayer = new ResizeLayer(size, ImageProcessor.Imaging.ResizeMode.Crop);
                        // Load, resize, set the format and quality and save an image.
                        imageFactory.Load(inStream)
                        .Resize(resizeLayer)
                        .Format(format)
                        .Quality(quality)
                        .Save(destinationFileName);
                    }
                }
            }
            return(true);
        }
Esempio n. 29
0
        public void SetImage(string path, Point position, Size size, ResizeMode mode = ResizeMode.Crop, AnchorPosition anchor = AnchorPosition.Center)
        {
            ImageLayer   imageLayer  = new ImageLayer();
            ResizeLayer  resizeLayer = new ResizeLayer(size, mode, anchor);
            ImageFactory temp        = new ImageFactory();

            temp.Load(new MemoryStream(File.ReadAllBytes(path)))
            .Resize(resizeLayer);

            imageLayer.Image    = temp.Image;
            imageLayer.Opacity  = 100;
            imageLayer.Position = position;

            _mainImageFactory.Overlay(imageLayer);
        }
Esempio n. 30
0
        /// <summary>
        /// Resizes the current image to the given dimensions.
        /// </summary>
        /// <param name="resizeLayer">
        /// The <see cref="ResizeLayer"/> containing the properties required to resize the image.
        /// </param>
        /// <returns>
        /// The current instance of the <see cref="T:ImageProcessor.ImageFactory"/> class.
        /// </returns>
        public ImageFactory Resize(ResizeLayer resizeLayer)
        {
            if (this.ShouldProcess)
            {
                var resizeSettings = new Dictionary <string, string> {
                    { "MaxWidth", resizeLayer.Size.Width.ToString("G") }, { "MaxHeight", resizeLayer.Size.Height.ToString("G") }
                };

                Resize resize = new Resize {
                    DynamicParameter = resizeLayer, Settings = resizeSettings
                };
                this.ApplyProcessor(resize.ProcessImage);
            }

            return(this);
        }