Encapsulates the properties required to resize an image.
        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;
            }
        }
Beispiel #2
1
        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();
        }
Beispiel #3
0
        /// <summary>
        /// Calculates the target location and bounds to perform the resize operation against.
        /// </summary>
        /// <param name="sourceSize">The source image size.</param>
        /// <param name="options">The resize options.</param>
        /// <param name="width">The target width.</param>
        /// <param name="height">The target height.</param>
        /// <returns>
        /// The tuple representing the location and the bounds.
        /// </returns>
        public static (Size, Rectangle) CalculateTargetLocationAndBounds(
            Size sourceSize,
            ResizeLayer options,
            int width,
            int height)
        {
            if (width <= 0 && height <= 0)
            {
                ThrowInvalid($"Target width {width} and height {height} must be greater than zero.");
            }

            switch (options.ResizeMode)
            {
            case ResizeMode.Crop:
                return(CalculateCropRectangle(sourceSize, options, width, height));

            case ResizeMode.Pad:
                return(CalculatePadRectangle(sourceSize, options, width, height));

            case ResizeMode.BoxPad:
                return(CalculateBoxPadRectangle(sourceSize, options, width, height));

            case ResizeMode.Max:
                return(CalculateMaxRectangle(sourceSize, width, height));

            case ResizeMode.Min:
                return(CalculateMinRectangle(sourceSize, width, height));

            // Last case ResizeMode.Stretch:
            default:
                return(new Size(width, height), new Rectangle(0, 0, width, height));
            }
        }
        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);
            }
        }
 public Stream Resize(Stream imageStream, int maxWidthOrHeight)
 {
     Size size = new Size(maxWidthOrHeight, maxWidthOrHeight);
     ResizeLayer layer = new ResizeLayer(size, ResizeMode.Max);
     Resizer resizer = new Resizer(layer);
     Bitmap bmp = resizer.ResizeImage(Image.FromStream(imageStream));
     return ToStream(bmp, ImageFormat.Jpeg);
 }
        /// <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 = "上传失败"

                });
            }

        }
        /// <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);
                }
                OSSHelper blob = new OSSHelper(AIHE.WebApi.Helpers.UtilityString.BlobString.YiQiHeHe);
              //  BlobHelper blob = new BlobHelper(BlobString.Portrait);
                string contentType = "image/jpeg";

               
                  blob.UploadFile(fileResized800Name, fileName, contentType);

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

                File.Delete(fileResized800Name);

                return Json(new ResponseMessageModel(new
                {
                    ImageName = fileName,
                    ImageUrl = CacheObjectHelper.SystemConfig.url_blob + fileName
                }));

          

            }

            catch (Exception ex)
            {
                return Json(new
                {
                    Code = 10,
                    Message = "上传失败"

                });
            }

        }
Beispiel #8
0
        /// <summary>
        /// Returns a value that indicates whether the specified object is an
        /// <see cref="ResizeLayer"/> object that is equivalent to
        /// this <see cref="ResizeLayer"/> object.
        /// </summary>
        /// <param name="obj">
        /// The object to test.
        /// </param>
        /// <returns>
        /// True if the given object  is an <see cref="ResizeLayer"/> object that is equivalent to
        /// this <see cref="ResizeLayer"/> object; otherwise, false.
        /// </returns>
        public override bool Equals(object obj)
        {
            ResizeLayer resizeLayer = obj as ResizeLayer;

            if (resizeLayer == null)
            {
                return(false);
            }

            return(this.Size == resizeLayer.Size &&
                   this.ResizeMode == resizeLayer.ResizeMode &&
                   this.AnchorPosition == resizeLayer.AnchorPosition &&
                   this.BackgroundColor == resizeLayer.BackgroundColor &&
                   this.Upscale == resizeLayer.Upscale);
        }
Beispiel #9
0
        /// <summary>
        /// Returns a value that indicates whether the specified object is an
        /// <see cref="ResizeLayer"/> object that is equivalent to
        /// this <see cref="ResizeLayer"/> object.
        /// </summary>
        /// <param name="obj">
        /// The object to test.
        /// </param>
        /// <returns>
        /// True if the given object  is an <see cref="ResizeLayer"/> object that is equivalent to
        /// this <see cref="ResizeLayer"/> object; otherwise, false.
        /// </returns>
        public override bool Equals(object obj)
        {
            ResizeLayer resizeLayer = obj as ResizeLayer;

            if (resizeLayer == null)
            {
                return(false);
            }

            return(this.Size == resizeLayer.Size &&
                   this.ResizeMode == resizeLayer.ResizeMode &&
                   this.AnchorPosition == resizeLayer.AnchorPosition &&
                   this.Upscale == resizeLayer.Upscale &&
                   this.CenterCoordinates.SequenceEqual(resizeLayer.CenterCoordinates) &&
                   this.MaxSize == resizeLayer.MaxSize &&
                   this.RestrictedSizes.SequenceEqual(resizeLayer.RestrictedSizes));
        }
Beispiel #10
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))
                {
                    Size size = new Size(200, 200);

                    ResizeLayer layer = new ResizeLayer(size);

                    imageFactory.Load(inStream)
                                .Resize(layer)
                                .Resolution(400, 400)
                                .Save(Path.GetFullPath(Path.Combine(outPath, fileInfo.Name)));

                    stopwatch.Stop();
                }

                // 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();
        }
Beispiel #11
0
		public void Resize()
		{
			byte[] imgBytes = File.ReadAllBytes(Path.FullName);
			using(MemoryStream inStream = new MemoryStream(imgBytes))
			{
				using(MemoryStream outStream = new MemoryStream())
				{
					using(ImageFactory factory = new ImageFactory(true))
					{
						ResizeLayer resizeLayer = new ResizeLayer(NewSize);
						resizeLayer.ResizeMode = ResizeMode.Stretch;
						factory.Load(inStream).Resize(resizeLayer).Save(outStream);
					}

					SaveFile(outStream);
				}
			}
			OnImageResized();
		}
Beispiel #12
0
        public byte[] CreatePreview(Stream stream, MediaTypes mediaType, Size size)
        {
            byte[] result;
            var format = mediaType.DetectFormat();
            var resizeLayer = new ResizeLayer(size, ResizeMode.Crop);

            stream.ResetStream();
            using (var outStream = new MemoryStream())
            {
                using (var imageFactory = new ImageFactory(preserveExifData: true))
                {
                    imageFactory.Load(stream)
                        .Format(format)
                        .Resize(resizeLayer)
                        .Save(outStream);
                }

                result = outStream.ToArray();
            }

            return result;
        }
Beispiel #13
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)
        {
            Image image = factory.Image;

            try
            {
                ImageLayer imageLayer = this.DynamicParameter;
                Bitmap overlay = new Bitmap(imageLayer.Image);

                // Set the resolution of the overlay and the image to match.
                overlay.SetResolution(image.HorizontalResolution, image.VerticalResolution);

                Size size = imageLayer.Size;
                int width = image.Width;
                int height = image.Height;
                int overlayWidth = size != Size.Empty ? Math.Min(width, size.Width) : Math.Min(width, overlay.Width);
                int overlayHeight = size != Size.Empty ? Math.Min(height, size.Height) : Math.Min(height, overlay.Height);

                Point? position = imageLayer.Position;
                int opacity = imageLayer.Opacity;

                if (image.Size != overlay.Size || image.Size != new Size(overlayWidth, overlayHeight))
                {
                    // Find the maximum possible dimensions and resize the image.
                    ResizeLayer layer = new ResizeLayer(new Size(overlayWidth, overlayHeight), ResizeMode.Max);
                    Resizer resizer = new Resizer(layer) { AnimationProcessMode = factory.AnimationProcessMode };
                    overlay = resizer.ResizeImage(overlay, factory.FixGamma);
                    overlayWidth = overlay.Width;
                    overlayHeight = overlay.Height;
                }

                // Figure out bounds.
                Rectangle parent = new Rectangle(0, 0, width, height);
                Rectangle child = new Rectangle(0, 0, overlayWidth, overlayHeight);

                // Apply opacity.
                if (opacity < 100)
                {
                    overlay = Adjustments.Alpha(overlay, opacity);
                }

                using (Graphics graphics = Graphics.FromImage(image))
                {
                    graphics.SmoothingMode = SmoothingMode.AntiAlias;
                    graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
                    graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
                    graphics.CompositingQuality = CompositingQuality.HighQuality;

                    if (position != null)
                    {
                        // Draw the image in position catering for overflow.
                        graphics.DrawImage(overlay, new Point(Math.Min(position.Value.X, width - overlayWidth), Math.Min(position.Value.Y, height - overlayHeight)));
                    }
                    else
                    {
                        RectangleF centered = ImageMaths.CenteredRectangle(parent, child);
                        graphics.DrawImage(overlay, new PointF(centered.X, centered.Y));
                    }
                }
            }
            catch (Exception ex)
            {
                throw new ImageProcessingException("Error processing image with " + this.GetType().Name, ex);
            }

            return image;
        }
        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");
            }
        }
        /// <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;
        }
        /// <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;
        }
Beispiel #17
0
        private Stream ProcessImage(IDocument input, ISupportedImageFormat format, ImageInstruction ins)
        {
            using (var imageFactory = new img.ImageFactory(preserveExifData: true))
            {
                // Load, resize, set the format and quality and save an image.
                img.ImageFactory fac;
                using (Stream stream = input.GetStream())
                {
                    fac = imageFactory.Load(stream).Format(format);
                }

                if (ins.IsNeedResize)
                {
                    if (ins.IsCropRequired)
                    {
                        var layer = new ResizeLayer(
                            size: ins.GetCropSize().Value,
                            anchorPosition: ins.GetAnchorPosition(),
                            resizeMode: ResizeMode.Crop
                            );

                        fac.Resize(layer);
                    }
                    else
                    {
                        fac.Resize(ins.GetCropSize().Value);
                    }
                }

                foreach (var f in ins.Filters)
                {
                    fac.Filter(ins.GetMatrixFilter(f));
                }

                if (ins.Brightness.HasValue)
                {
                    fac.Brightness(ins.Brightness.Value);
                }

                if (ins.Constraint.HasValue)
                {
                    fac.Constrain(ins.Constraint.Value);
                }

                if (ins.Opacity.HasValue)
                {
                    fac.Alpha(ins.Opacity.Value);
                }

                if (ins.Hue != null)
                {
                    fac.Hue(ins.Hue.Degrees, ins.Hue.Rotate);
                }

                if (ins.Tint != null)
                {
                    fac.Tint(ins.Tint.Value);
                }

                if (ins.Vignette != null)
                {
                    fac.Vignette(ins.Vignette.Value);
                }

                if (ins.Saturation.HasValue)
                {
                    fac.Saturation(ins.Saturation.Value);
                }

                if (ins.Contrast.HasValue)
                {
                    fac.Contrast(ins.Contrast.Value);
                }

                var outputStream = new MemoryStream();
                fac.Save(outputStream);
                outputStream.Seek(0, SeekOrigin.Begin);
                return outputStream;
            }
        }
Beispiel #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)
        {
            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);
                ResizeMode mode = QueryParamParser.Instance.ParseValue<ResizeMode>(queryCollection["mode"]);
                AnchorPosition position = QueryParamParser.Instance.ParseValue<AnchorPosition>(queryCollection["anchor"]);
                bool upscale = queryCollection["upscale"] == null || QueryParamParser.Instance.ParseValue<bool>(queryCollection["upscale"]);
                float[] center = queryCollection["center"] != null
                                    ? QueryParamParser.Instance.ParseValue<float[]>(queryCollection["center"]) :
                                    new float[] { };

                ResizeLayer resizeLayer = new ResizeLayer(size)
                {
                    ResizeMode = mode,
                    AnchorPosition = position,
                    Upscale = upscale,
                    CenterCoordinates = center
                };

                this.Processor.DynamicParameter = resizeLayer;

                // Correctly parse any restrictions.
                string restrictions;
                this.Processor.Settings.TryGetValue("RestrictTo", out restrictions);

                List<Size> restrictedSizes = this.ParseRestrictions(restrictions);

                if (restrictedSizes != null && restrictedSizes.Any())
                {
                    bool reject = true;
                    foreach (Size restrictedSize in restrictedSizes)
                    {
                        if (restrictedSize.Height == 0 || restrictedSize.Width == 0)
                        {
                            if (restrictedSize.Width == size.Width || restrictedSize.Height == size.Height)
                            {
                                reject = false;
                            }
                        }
                        else if (restrictedSize.Width == size.Width && restrictedSize.Height == size.Height)
                        {
                            reject = false;
                        }
                    }

                    if (reject)
                    {
                        throw new HttpException((int)HttpStatusCode.Forbidden, string.Format("The given size: {0}x{1} is not allowed.", size.Width, size.Height));
                    }
                }

                ((ImageProcessor.Processors.Resize)this.Processor).RestrictedSizes = this.ParseRestrictions(restrictions);
            }

            return this.SortOrder;
        }
        /// <summary>
        /// 上传图片
        /// </summary>
        /// <returns></returns>
        public async Task<IHttpActionResult> Post()
        {

              //如果不含文件就退出
            if (!HttpContext.Current.Request.Files.AllKeys.Any())
            {
                return Json(new
                {
                    Code = 1
                });
            }
           
            var httpPostedFile = HttpContext.Current.Request.Files[0];
            if (httpPostedFile == null)
            {
                return Json(new
                {
                    Code = 1
                });
            }
            BlobHelper blob = new BlobHelper(BlobString.Portrait);
            string fileName = Guid.NewGuid().ToString();
            blob.Upload( httpPostedFile, fileName);
            bool isPicture = false;
           
            switch(httpPostedFile.ContentType)
            {
                case  "image/jpeg": 
                case  "image/png":
                    isPicture = true;

                    break;
                 

                default:
                    break;
            }
            //插入数据库,如果是图像文件,生成缩略图,大图
            DataBaseEntities db = new DataBaseEntities();
            pm_Attach attach = new pm_Attach
            {
                AddDate = DateTime.Now,
                AttachId = Guid.NewGuid().ToString(),
                ContentType = httpPostedFile.ContentType,
                IsPicture = isPicture,
                VersionId = HttpContext.Current.Request.Form["versionid"],
                Url = "http://hdy.awblob.com/portrait/" + fileName,
                 DisplayName = httpPostedFile.FileName
            };
            db.pm_Attach.Add(attach);
            db.SaveChanges();

            if (isPicture)
            {
                string fileSaveName = Guid.NewGuid() + ".jpg";
                var fileOrginalFile = Path.Combine(HttpContext.Current.Server.MapPath("~/Upload"), fileSaveName);
                httpPostedFile.SaveAs(fileOrginalFile);

                string fileResized300Name = HttpContext.Current.Server.MapPath("~/upload/" + Guid.NewGuid().ToString() + ".jpg");
                using (var imageFactory = new ImageFactory(preserveExifData: true))
                {

                    System.Drawing.Size size = new System.Drawing.Size(300, 300);
                    ResizeLayer resize = new ResizeLayer(size, ResizeMode.Crop);
                    imageFactory.Load(fileOrginalFile).Resize(resize).Save(fileResized300Name);
                }
                await blob.UploadFile(fileResized300Name, fileName+"-preview", httpPostedFile.ContentType);

                string fileResizedBigName = HttpContext.Current.Server.MapPath("~/upload/" + Guid.NewGuid().ToString() + ".jpg");
                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(fileResizedBigName);
                }

                await blob.UploadFile(fileResizedBigName, fileName + "-big", httpPostedFile.ContentType);

            }

           



           


            // Get the uploaded image from the Files collection




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

        }
        /// <summary>
        /// 上传图片
        /// </summary>
        /// <returns></returns>
        public async Task<IHttpActionResult> Post()
        {
            try
            {
                if (!HttpContext.Current.Request.Form.HasKeys())
                {
                    CommonRequestHelper.ThrowErrorMessage("上传失败");
                }

                DataBaseEntities db = new DataBaseEntities();
                OSSHelper blob = new OSSHelper(AIHE.WebApi.Helpers.UtilityString.BlobString.YiQiHeHe);

              
                switch (HttpContext.Current.Request.Files.Count)
                {
                    case 0:
                        {
                            var news0 = new tb_JiuYouQuan
                            {
                                AddDate = UtilityHelper.getNow(),
                                Description = HttpContext.Current.Request.Form["content"],
                                id = Guid.NewGuid().ToString(),
                                IsHot = false,
                                Islegal = true,
                                SingleHeight = 0,
                                SingleWidth = 0,
                                UserId = User.Identity.GetUserId(),
                                Images = ""
                            };
                            db.tb_JiuYouQuan.Add(news0);
                            db.SaveChanges();
                       
                            return Json(new ResponseMessageModel(true));


                        }
                      
                        break;
                    case 1:
                        //只有一个文件
                        #region
                        string fileOrginalFile = HttpContext.Current.Server.MapPath("~/MyUpload/" + Guid.NewGuid().ToString() + ".jpg");

                        HttpContext.Current.Request.Files[0].SaveAs(fileOrginalFile);
                        Image pic = Image.FromFile(fileOrginalFile);//strFilePath是该图片的绝对路径
                        int intWidth = pic.Width;//长度像素值
                        int intHeight = pic.Height;//高度像素值 
                        int newWidth = intWidth;
                        int newHeight = intHeight;
                        string fileResizedName = HttpContext.Current.Server.MapPath("/MyUpload/" + Guid.NewGuid().ToString() + ".jpg");
                        string saveFileName = Guid.NewGuid().ToString();
                          blob.UploadFile(fileOrginalFile, saveFileName + "-big");


                        if (intWidth > 135 || intHeight > 135)
                        {
                            using (var imageFactory = new ImageFactory(preserveExifData: true))
                            {


                                if (intWidth > intHeight)
                                {
                                    newWidth = 135;
                                    newHeight = (int)(Convert.ToDouble(intHeight) / Convert.ToDouble(intWidth) * 135);
                                }
                                else
                                {
                                    newHeight = 135;
                                    newWidth = (int)(Convert.ToDouble(intWidth) / Convert.ToDouble(intHeight) * 135);
                                }

                                System.Drawing.Size size = new System.Drawing.Size(newWidth * 2, newHeight * 2);
                                imageFactory.Load(fileOrginalFile).Resize(size).Save(fileResizedName);
                            }
                              blob.UploadFile(fileResizedName, saveFileName);  //缩略图应该是同步程序
                        }
                        else
                        {
                              blob.UploadFile(fileOrginalFile, saveFileName);   //缩略图应该是同步程序
                        }

                        var news1 = new tb_JiuYouQuan
                        {
                            AddDate = UtilityHelper.getNow(),
                            Description = HttpContext.Current.Request.Form["content"],
                            id = Guid.NewGuid().ToString(),
                            Images = saveFileName,
                            IsHot = false,
                            Islegal = true,
                            SingleHeight = newHeight,
                            SingleWidth = newWidth,
                            UserId = User.Identity.GetUserId()
                        };
                        pic.Dispose();
                        File.Delete(fileOrginalFile);

                        File.Delete(fileResizedName);
                        db.tb_JiuYouQuan.Add(news1);
                        db.SaveChanges();
                        return Json(new ResponseMessageModel(true));

                    //删除文件

                        #endregion

                    default:
                        List<string> newsFiles = new List<string>();
                        for (var i = 0; i < HttpContext.Current.Request.Files.Count; i++)
                        {
                            var savedName = Guid.NewGuid().ToString();
                            var fileCropName = HttpContext.Current.Server.MapPath("/MyUpload/" + Guid.NewGuid().ToString() + ".jpg");
                            var orginal = HttpContext.Current.Server.MapPath("~/MyUpload/" + Guid.NewGuid().ToString() + ".jpg");
                            HttpContext.Current.Request.Files[i].SaveAs(orginal);
                              blob.UploadFile(orginal, savedName + "-big");

                            using (var imageFactory = new ImageFactory(preserveExifData: true))
                            {
                                // Do your magic here
                                System.Drawing.Size size = new System.Drawing.Size(70 *2, 70*2);
                                ResizeLayer resize = new ResizeLayer(size, ResizeMode.Crop);
                                imageFactory.Load(orginal).Resize(resize).Save(fileCropName);
                            }
                            bool flagCrop =   blob.UploadFile(fileCropName, savedName);

                            if (flagCrop)
                            {
                                newsFiles.Add(savedName);

                            }
                            File.Delete(orginal);

                            File.Delete(fileCropName);

                        }

                        if (newsFiles.Count == 0)
                        {

                            CommonRequestHelper.ThrowErrorMessage("上传失败");
                        }
                       


                            var newsMultiple = new tb_JiuYouQuan
                            {
                                AddDate = UtilityHelper.getNow(),
                                Description = HttpContext.Current.Request.Form["content"],
                                id = Guid.NewGuid().ToString(),
                                Images = string.Join(";", newsFiles),
                                IsHot = false,
                                Islegal = true,
                                SingleHeight = 0,
                                SingleWidth = 0,
                                UserId = User.Identity.GetUserId()
                            };
                            db.tb_JiuYouQuan.Add(newsMultiple);
                            db.SaveChanges();

                       

                              return Json(new ResponseMessageModel(true));
                      

                        break;

                }




            }

            catch (Exception ex)
            {
                
                CommonRequestHelper.ThrowErrorMessage("上传失败");
                return null;
            }
        }
        public async Task<IHttpActionResult> fileUpload()
        {
            //如果不含文件就退出
            if (!HttpContext.Current.Request.Files.AllKeys.Any())
            {
                return Json(new
                {
                    Code = 1
                });
            }
            string fileName = Guid.NewGuid().ToString();
            var httpPostedFile = HttpContext.Current.Request.Files[0];

            if (httpPostedFile == null)
            {
                return Json(new
                {
                    Code = 1

                });
            }
            string fileExtension = System.IO.Path.GetExtension(HttpContext.Current.Request.Form["file"]).ToLower();
            if (fileExtension == "")
            {
                fileExtension = ".jpg";
            }

            var fileOrginalFile = Path.Combine(HttpContext.Current.Server.MapPath("~/Upload"), fileName + fileExtension);

            // Save the uploaded file to "UploadedFiles" folder
            httpPostedFile.SaveAs(fileOrginalFile);




            string fileResized300Name = HttpContext.Current.Server.MapPath("~/upload/" + Guid.NewGuid().ToString() + fileExtension);
            using (var imageFactory = new ImageFactory(preserveExifData: true))
            {

                System.Drawing.Size size = new System.Drawing.Size(300, 300);
                ResizeLayer resize = new ResizeLayer(size, ResizeMode.Crop);
                imageFactory.Load(fileOrginalFile).Resize(resize).Save(fileResized300Name);


            }

            BlobHelper blob = new BlobHelper(BlobString.Portrait);



            string contentType = "application/octet-stream";

            switch (fileExtension)
            {
                case ".jpg":
                case ".jpeg":
                    contentType = "image/jpeg";
                    break;
                case ".png":
                    contentType = "image/png";
                    break;
                default:
                    contentType = "application/octet-stream";
                    break;
            }


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


            // Get the uploaded image from the Files collection




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

        }
Beispiel #22
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);
                    //}
                }

            }
        }
        /// <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;

                Dictionary<string, string> resizeSettings = new Dictionary<string, string> { { "MaxWidth", width.ToString("G") }, { "MaxHeight", height.ToString("G") } };

                ResizeLayer resizeLayer = new ResizeLayer(new Size(width, height));

                Resize resize = new Resize { DynamicParameter = resizeLayer, Settings = resizeSettings };

                this.Image = resize.ProcessImage(this);
            }

            return this;
        }
Beispiel #24
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Resizer"/> class.
 /// </summary>
 /// <param name="resizeLayer">
 /// The <see cref="ResizeLayer"/>.
 /// </param>
 public Resizer(ResizeLayer resizeLayer)
 {
     this.ResizeLayer = resizeLayer;
 }
Beispiel #25
0
        public IActionResult Download([FromRoute] string filepath)
        {
            //TODO  authorize
            if (string.IsNullOrWhiteSpace(filepath))
                return DoPageNotFoundResponse();

            if (!filepath.StartsWith("/"))
                filepath = "/" + filepath;

            filepath = filepath.ToLowerInvariant();

            DbFileRepository fsRepository = new DbFileRepository();
            var file = fsRepository.Find(filepath);

            if (file == null)
                return DoPageNotFoundResponse();

            //check for modification
            string headerModifiedSince = Request.Headers["If-Modified-Since"];
            if (headerModifiedSince != null)
            {
                DateTime isModifiedSince;
                if (DateTime.TryParse(headerModifiedSince, out isModifiedSince))
                {
                    if (isModifiedSince <= file.LastModificationDate)
                    {
                        Response.StatusCode = 304;
                        return new EmptyResult();
                    }
                }
            }

            HttpContext.Response.Headers.Add("last-modified", file.LastModificationDate.ToString());

            string mimeType;
            var extension = Path.GetExtension(filepath).ToLowerInvariant();
            new FileExtensionContentTypeProvider().Mappings.TryGetValue(extension, out mimeType);

            IDictionary<string, StringValues> queryCollection = Microsoft.AspNetCore.WebUtilities.QueryHelpers.ParseQuery(HttpContext.Request.QueryString.ToString());
            string action = queryCollection.Keys.Any(x => x == "action") ? ((string)queryCollection["action"]).ToLowerInvariant() : "";
            string requestedMode = queryCollection.Keys.Any(x => x == "mode") ? ((string)queryCollection["mode"]).ToLowerInvariant() : "";
            string width = queryCollection.Keys.Any(x => x == "width") ? ((string)queryCollection["width"]).ToLowerInvariant() : "";
            string height = queryCollection.Keys.Any(x => x == "height") ? ((string)queryCollection["height"]).ToLowerInvariant() : "";
            bool isImage = extension == ".jpg" || extension == ".jpeg" || extension == ".png" || extension == ".gif";
            if (isImage && (!string.IsNullOrWhiteSpace(action) || !string.IsNullOrWhiteSpace(requestedMode) || !string.IsNullOrWhiteSpace(width) || !string.IsNullOrWhiteSpace(height)))
            {
                var fileContent = file.GetBytes();
                using (ImageFactory imageFactory = new ImageFactory())
                {
                    using (Stream inStream = new MemoryStream(fileContent))
                    {

                        MemoryStream outStream = new MemoryStream();
                        imageFactory.Load(inStream);

                        //sets background
                        System.Drawing.Color backgroundColor = System.Drawing.Color.White;
                        switch (imageFactory.CurrentImageFormat.MimeType)
                        {
                            case "image/gif":
                            case "image/png":
                                backgroundColor = System.Drawing.Color.Transparent;
                                break;
                            default:
                                break;
                        }

                        switch (action)
                        {
                            default:
                            case "resize":
                                {
                                    ResizeMode mode;
                                    switch (requestedMode)
                                    {
                                        case "boxpad":
                                            mode = ResizeMode.BoxPad;
                                            break;
                                        case "crop":
                                            mode = ResizeMode.Crop;
                                            break;
                                        case "min":
                                            mode = ResizeMode.Min;
                                            break;
                                        case "max":
                                            mode = ResizeMode.Max;
                                            break;
                                        case "stretch":
                                            mode = ResizeMode.Stretch;
                                            break;
                                        default:
                                            mode = ResizeMode.Pad;
                                            break;
                                    }

                                    Size size = ParseSize(queryCollection);
                                    ResizeLayer rl = new ResizeLayer(size, mode);
                                    imageFactory.Resize(rl).BackgroundColor(backgroundColor).Save(outStream);
                                }
                                break;
                        }

                        outStream.Seek(0, SeekOrigin.Begin);
                        return File(outStream, mimeType);
                    }
                }
            }

            return File(file.GetBytes(), mimeType);
        }
Beispiel #26
0
        private static (Size, Rectangle) CalculateBoxPadRectangle(
            Size source,
            ResizeLayer options,
            int width,
            int height)
        {
            if (width <= 0 || height <= 0)
            {
                return(new Size(source.Width, source.Height), new Rectangle(0, 0, source.Width, source.Height));
            }

            int sourceWidth  = source.Width;
            int sourceHeight = source.Height;

            // Fractional variants for preserving aspect ratio.
            float percentHeight = Math.Abs(height / (float)sourceHeight);
            float percentWidth  = Math.Abs(width / (float)sourceWidth);

            int boxPadHeight = height > 0 ? height : (int)Math.Round(sourceHeight * percentWidth);
            int boxPadWidth  = width > 0 ? width : (int)Math.Round(sourceWidth * percentHeight);

            // Only calculate if upscaling.
            if (sourceWidth < boxPadWidth && sourceHeight < boxPadHeight)
            {
                int destinationX;
                int destinationY;
                int destinationWidth  = sourceWidth;
                int destinationHeight = sourceHeight;
                width  = boxPadWidth;
                height = boxPadHeight;

                switch (options.AnchorPosition)
                {
                case AnchorPosition.Left:
                    destinationY = (height - sourceHeight) / 2;
                    destinationX = 0;
                    break;

                case AnchorPosition.Right:
                    destinationY = (height - sourceHeight) / 2;
                    destinationX = width - sourceWidth;
                    break;

                case AnchorPosition.TopRight:
                    destinationY = 0;
                    destinationX = width - sourceWidth;
                    break;

                case AnchorPosition.Top:
                    destinationY = 0;
                    destinationX = (width - sourceWidth) / 2;
                    break;

                case AnchorPosition.TopLeft:
                    destinationY = 0;
                    destinationX = 0;
                    break;

                case AnchorPosition.BottomRight:
                    destinationY = height - sourceHeight;
                    destinationX = width - sourceWidth;
                    break;

                case AnchorPosition.Bottom:
                    destinationY = height - sourceHeight;
                    destinationX = (width - sourceWidth) / 2;
                    break;

                case AnchorPosition.BottomLeft:
                    destinationY = height - sourceHeight;
                    destinationX = 0;
                    break;

                default:
                    destinationY = (height - sourceHeight) / 2;
                    destinationX = (width - sourceWidth) / 2;
                    break;
                }

                return(new Size(width, height),
                       new Rectangle(destinationX, destinationY, destinationWidth, destinationHeight));
            }

            // Switch to pad mode to downscale and calculate from there.
            return(CalculatePadRectangle(source, options, width, height));
        }
        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);
        }
Beispiel #28
0
        private static (Size, Rectangle) CalculateCropRectangle(
            Size source,
            ResizeLayer options,
            int width,
            int height)
        {
            float ratio;
            int   sourceWidth  = source.Width;
            int   sourceHeight = source.Height;

            int targetX      = 0;
            int targetY      = 0;
            int targetWidth  = width;
            int targetHeight = height;

            // Fractional variants for preserving aspect ratio.
            float percentHeight = Math.Abs(height / (float)sourceHeight);
            float percentWidth  = Math.Abs(width / (float)sourceWidth);

            if (percentHeight < percentWidth)
            {
                ratio = percentWidth;

                if (options.Center is var center && center.HasValue)
                {
                    float centerRatio = -(ratio * sourceHeight) * center.Value.Y;
                    targetY = (int)Math.Round(centerRatio + (height / 2F));

                    if (targetY > 0)
                    {
                        targetY = 0;
                    }

                    if (targetY < (int)Math.Round(height - (sourceHeight * ratio)))
                    {
                        targetY = (int)Math.Round(height - (sourceHeight * ratio));
                    }
                }
                else
                {
                    switch (options.AnchorPosition)
                    {
                    case AnchorPosition.Top:
                    case AnchorPosition.TopLeft:
                    case AnchorPosition.TopRight:
                        targetY = 0;
                        break;

                    case AnchorPosition.Bottom:
                    case AnchorPosition.BottomLeft:
                    case AnchorPosition.BottomRight:
                        targetY = (int)Math.Round(height - (sourceHeight * ratio));
                        break;

                    default:
                        targetY = (int)Math.Round((height - (sourceHeight * ratio)) / 2F);
                        break;
                    }
                }

                targetHeight = (int)Math.Ceiling(sourceHeight * percentWidth);
            }
Beispiel #29
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)
        {
            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);
                ResizeMode mode = QueryParamParser.Instance.ParseValue<ResizeMode>(queryCollection["mode"]);
                AnchorPosition position = QueryParamParser.Instance.ParseValue<AnchorPosition>(queryCollection["anchor"]);
                bool upscale = queryCollection["upscale"] == null || QueryParamParser.Instance.ParseValue<bool>(queryCollection["upscale"]);
                float[] center = queryCollection["center"] != null
                                    ? QueryParamParser.Instance.ParseValue<float[]>(queryCollection["center"]) :
                                    new float[] { };

                ResizeLayer resizeLayer = new ResizeLayer(size)
                {
                    ResizeMode = mode,
                    AnchorPosition = position,
                    Upscale = upscale,
                    CenterCoordinates = center
                };

                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;
        }
Beispiel #30
0
        /// <summary>
        /// The main routine.
        /// </summary>
        /// <param name="args">
        /// The args.
        /// </param>
        public static void Main(string[] args)
        {
            string path = new Uri(System.Reflection.Assembly.GetExecutingAssembly().CodeBase).LocalPath;

            // ReSharper disable once AssignNullToNotNullAttribute
            string resolvedPath = Path.GetFullPath(Path.Combine(Path.GetDirectoryName(path), @"..\..\images\input"));
            DirectoryInfo di = new DirectoryInfo(resolvedPath);
            if (!di.Exists)
            {
                di.Create();
            }

            // Image mask = Image.FromFile(Path.Combine(resolvedPath, "mask.png"));
            // Image overlay = Image.FromFile(Path.Combine(resolvedPath, "imageprocessor.128.png"));
            //FileInfo fileInfo = new FileInfo(Path.Combine(resolvedPath, "2008.jpg"));
            //FileInfo fileInfo = new FileInfo(Path.Combine(resolvedPath, "stretched.jpg"));
            //FileInfo fileInfo = new FileInfo(Path.Combine(resolvedPath, "mountain.jpg"));
            //FileInfo fileInfo = new FileInfo(Path.Combine(resolvedPath, "blur-test.png"));
            // FileInfo fileInfo = new FileInfo(Path.Combine(resolvedPath, "earth_lights_4800.tif"));
            //FileInfo fileInfo = new FileInfo(Path.Combine(resolvedPath, "gamma-1.0-or-2.2.png"));
            //FileInfo fileInfo = new FileInfo(Path.Combine(resolvedPath, "gamma_dalai_lama_gray.jpg"));
            //FileInfo fileInfo = new FileInfo(Path.Combine(resolvedPath, "Arc-de-Triomphe-France.jpg"));
            //FileInfo fileInfo = new FileInfo(Path.Combine(resolvedPath, "Martin-Schoeller-Jack-Nicholson-Portrait.jpeg"));
            //FileInfo fileInfo = new FileInfo(Path.Combine(resolvedPath, "night-bridge.png"));
            //FileInfo fileInfo = new FileInfo(Path.Combine(resolvedPath, "tree.jpg"));
            //FileInfo fileInfo = new FileInfo(Path.Combine(resolvedPath, "blue-balloon.jpg"));
            //FileInfo fileInfo = new FileInfo(Path.Combine(resolvedPath, "test2.png"));
            //FileInfo fileInfo = new FileInfo(Path.Combine(resolvedPath, "120430.gif"));
            //FileInfo fileInfo = new FileInfo(Path.Combine(resolvedPath, "rickroll.original.gif"));

            //////FileInfo fileInfo = new FileInfo(Path.Combine(resolvedPath, "crop-base-300x200.jpg"));
            //FileInfo fileInfo = new FileInfo(Path.Combine(resolvedPath, "cmyk.png"));
            //IEnumerable<FileInfo> files = GetFilesByExtensions(di, ".gif");
            //IEnumerable<FileInfo> files = GetFilesByExtensions(di, ".png", ".jpg", ".jpeg");
               // IEnumerable<FileInfo> files = GetFilesByExtensions(di, ".jpg", ".jpeg", ".jfif");
            IEnumerable<FileInfo> files = GetFilesByExtensions(di, ".png");
            //IEnumerable<FileInfo> files = GetFilesByExtensions(di, ".gif", ".webp", ".bmp", ".jpg", ".png");

            foreach (FileInfo fileInfo in files)
            {
                if (fileInfo.Name == "test5.jpg")
                {
                    continue;
                }

            byte[] photoBytes = File.ReadAllBytes(fileInfo.FullName);
            Console.WriteLine("Processing: " + fileInfo.Name);

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

            // ImageProcessor
            using (MemoryStream inStream = new MemoryStream(photoBytes))
            {
                using (ImageFactory imageFactory = new ImageFactory(true, true))
                {
                    Size size = new Size(1920, 1920);
                    //CropLayer cropLayer = new CropLayer(20, 20, 20, 20, ImageProcessor.Imaging.CropMode.Percentage);
                    ResizeLayer layer = new ResizeLayer(size, ResizeMode.Max, AnchorPosition.Center, false);
                    // TextLayer textLayer = new TextLayer()
                    //{
                    //    Text = "هناك حقيقة مثبتة منذ زمن",
                    //    FontColor = Color.White,
                    //    DropShadow = true,
                    //    Vertical = true,
                    //    //RightToLeft = true,
                    //    //Position = new Point(5, 5)

                    //};

                    //ContentAwareResizeLayer layer = new ContentAwareResizeLayer(size)
                    //{
                    //    ConvolutionType = ConvolutionType.Sobel
                    //};
                    // Load, resize, set the format and quality and save an image.
                    imageFactory.Load(inStream)
                        //.DetectObjects(EmbeddedHaarCascades.FrontFaceDefault)
                        //.Overlay(new ImageLayer
                        //            {
                        //                Image = overlay,
                        //                Opacity = 50
                        //            })
                        //.Alpha(50)
                        //.BackgroundColor(Color.White)
                        //.Resize(new Size((int)(size.Width * 1.1), 0))
                        //.ContentAwareResize(layer)
                        //.Constrain(size)
                        //.Mask(mask)
                        //.Format(new PngFormat())
                        //.BackgroundColor(Color.Cyan)
                        //.Watermark(textLayer)
                        //.ReplaceColor(Color.FromArgb(93, 136, 231), Color.FromArgb(94, 134, 78), 50)
                        //.GaussianSharpen(3)
                        //.Saturation(20)
                        //.Resize(size)
                        .Resize(layer)
                        // .Resize(new ResizeLayer(size, ResizeMode.Stretch))
                        //.DetectEdges(new SobelEdgeFilter(), true)
                        //.DetectEdges(new LaplacianOfGaussianEdgeFilter())
                        //.GaussianBlur(new GaussianLayer(10, 11))
                        //.EntropyCrop()
                        //.Gamma(2.2F)
                        //.Halftone()
                        //.RotateBounded(150, false)
                        //.Crop(cropLayer)
                        //.Rotate(140)
                        //.Filter(MatrixFilters.Invert)
                        //.Brightness(-5)
                        //.Contrast(50)
                        //.Filter(MatrixFilters.Comic)
                        //.Flip()
                        //.Filter(MatrixFilters.HiSatch)
                        //.Pixelate(8)
                        //.GaussianSharpen(10)
                        //.Format(new PngFormat() { IsIndexed = true })
                        //.Format(new PngFormat() )
                        .Save(Path.GetFullPath(Path.Combine(Path.GetDirectoryName(path), @"..\..\images\output", fileInfo.Name)));
                    //.Save(Path.GetFullPath(Path.Combine(Path.GetDirectoryName(path), @"..\..\images\output", Path.GetFileNameWithoutExtension(fileInfo.Name) + ".png")));

                    stopwatch.Stop();
                }
            }

            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.WriteLine("Processed: " + fileInfo.Name + " in " + stopwatch.ElapsedMilliseconds + "ms");
               }

            Console.ReadLine();
        }
        /// <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)
            {
                Dictionary<string, string> 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.CurrentImageFormat.ApplyProcessor(resize.ProcessImage, this);
            }

            return this;
        }
Beispiel #32
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)
                {
                    if (index == 0)
                    {
                        // Set the index on the first instance only.
                        this.SortOrder = match.Index;
                    }

                    stringBuilder.Append(match.Value);

                    index += 1;
                }
            }

            // Match syntax
            string toParse = stringBuilder.ToString();

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

            this.DynamicParameter = resizeLayer;
            return this.SortOrder;
        }
        public async Task<IHttpActionResult> Post()
        {
           
            string itemid=HttpContext.Current.Request.Form["itemid"];
            string fileName = Guid.NewGuid().ToString();
            // 检查是否是 multipart/form-data
            //if (!Request.Content.IsMimeMultipartContent("form-data"))
            //{
            //    return Json(new
            //    {
            //        Code = 20000,
            //        Detail = new
            //        {

            //            Description = "没有文件"

            //        }

            //    });
            //}

            

            // Stream img = Request.Content.ReadAsStreamAsync();
            try
            {
                string fileOrginalFile = HttpContext.Current.Server.MapPath("~/MyUpload/Orignal/" + fileName + ".jpg");
                string fileResized150Name = HttpContext.Current.Server.MapPath("~/MyUpload/Resize150/" + fileName + ".jpg");
                string fileResized800Name = HttpContext.Current.Server.MapPath("~/MyUpload/Resize800/" + fileName + ".jpg");
             //   HttpContext.Current.Request.Files[0].SaveAs(fileOrginalFile);

                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(200, 200);
                    imageFactory.Load(fileOrginalFile).Resize(size).Save(fileResized150Name);
                    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(fileResized150Name, fileName, contentType);
                await blob.UploadFile(fileResized800Name, fileName + "-big", contentType);

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


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

            }

            catch (Exception ex)
            {
                return Json(new
                {
                    Code = 10,
                    Message="上传失败"

                });
            }

        }
 /// <summary>
 /// Initializes a new instance of the <see cref="StubbedResizer"/> class.
 /// </summary>
 /// <param name="resizeLayer">
 /// The <see cref="ResizeLayer"/>.
 /// </param>
 public StubbedResizer(ResizeLayer resizeLayer) : base(resizeLayer)
 {
 }
Beispiel #35
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Resizer"/> class.
 /// </summary>
 /// <param name="resizeLayer">
 /// The <see cref="ResizeLayer"/>.
 /// </param>
 public Resizer(ResizeLayer resizeLayer)
 {
     this.ResizeLayer = resizeLayer;
 }
        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);

            Size padSingleDimensionWidthSize = new Size(400, 0);
            // ReSharper disable once RedundantArgumentDefaultValue
            ResizeLayer paddedSingleDimensionWidthLayer = new ResizeLayer(padSingleDimensionWidthSize, ResizeMode.Pad);

            Size padSingleDimensionHeightSize = new Size(0, 300);
            // ReSharper disable once RedundantArgumentDefaultValue
            ResizeLayer paddedSingleDimensionHeightLayer = new ResizeLayer(padSingleDimensionHeightSize, ResizeMode.Pad);

            Size boxPadSingleDimensionWidthSize = new Size(400, 0);
            ResizeLayer boxPadSingleDimensionWidthLayer = new ResizeLayer(boxPadSingleDimensionWidthSize, ResizeMode.BoxPad);

            Size boxPadSingleDimensionHeightSize = new Size(0, 300);
            ResizeLayer boxPadSingleDimensionHeightLayer = new ResizeLayer(boxPadSingleDimensionHeightSize, ResizeMode.BoxPad);

            int i = 0;
            foreach (ImageFactory imageFactory in this.ListInputImages(".gif"))
            {
                Image original = imageFactory.Image.Copy();

                // 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(OutputPath + "resize-stretch-" + i + ".jpg");

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

                // Check we crop correctly.
                imageFactory.Resize(cropLayer);
                Assert.AreEqual(imageFactory.Image.Size, cropSize);
                imageFactory.Save(OutputPath + "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(OutputPath + "resize-crop-" + i + ".jpg");

                // Check padding with only a single dimension specified (width)
                imageFactory.Resize(paddedSingleDimensionWidthLayer);
                Assert.AreEqual(imageFactory.Image.Size, new Size(400, 300));
                imageFactory.Save(OutputPath + "resize-padsingledimension-width-" + i + ".jpg");

                // Check padding with only a single dimension specified (height)
                imageFactory.Resize(paddedSingleDimensionHeightLayer);
                Assert.AreEqual(imageFactory.Image.Size, new Size(400, 300));
                imageFactory.Save(OutputPath + "resize-padsingledimension-height-" + i + ".jpg");

                // Check box padding with only a single dimension specified (width)
                imageFactory.Resize(boxPadSingleDimensionWidthLayer);
                Assert.AreEqual(imageFactory.Image.Size, new Size(400, 300));
                imageFactory.Save(OutputPath + "resize-boxpadsingledimension-width-" + i + ".jpg");

                // Check box padding with only a single dimension specified (height)
                imageFactory.Resize(boxPadSingleDimensionHeightLayer);
                Assert.AreEqual(imageFactory.Image.Size, new Size(400, 300));
                imageFactory.Save(OutputPath + "resize-boxpadsingledimension-height-" + i + ".jpg");

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

                imageFactory.Format(new JpegFormat()).Save(OutputPath + "resize-" + i + ".jpg");
            }
        }