Beispiel #1
0
        public async Task <IActionResult> Post()
        {
            if (Request.Form.Files.Count != 1)
            {
                throw new InvalidOperationException("Invalid upload!");
            }

            IFormFile file = Request.Form.Files.First();

            if (!(string.Equals("image/jpeg", file.ContentType, StringComparison.OrdinalIgnoreCase) ||
                  string.Equals("image/jpg", file.ContentType, StringComparison.OrdinalIgnoreCase) ||
                  string.Equals("image/png", file.ContentType, StringComparison.OrdinalIgnoreCase)))
            {
                throw new InvalidOperationException("Invalid content type. Only support JPG and PNG images.");
            }

            string actualFileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');

            Console.WriteLine(file.ContentType);
            FileInfo fi       = new FileInfo(actualFileName);
            string   fileName = string.Format(CultureInfo.InvariantCulture, "{0}{1}", Guid.NewGuid().ToString("N").Substring(0, 8), fi.Extension);

            ResizeResult result = null;

            try
            {
                using (Stream stream = file.OpenReadStream())
                {
                    result = await this.imageProvider.Resize(fileName, stream);
                }
            }
            catch (Exception ex)
            {
                this.loggerFactory.CreateLogger("Default").LogError("", ex);
                throw;
            }

            return(new ObjectResult(new
            {
                originUrl = result.UriActualSize,
                url = result.UriResizedSize
            }));
        }
Beispiel #2
0
 /// <summary>
 /// Hits the test to cursor.
 /// </summary>
 /// <param name="result">The result.</param>
 /// <returns>Cursor.</returns>
 public static Cursor HitTestToCursor(ResizeResult result)
 {
     if ((result == ResizeResult.Left) || result == ResizeResult.Right)
     {
         return(Cursors.SizeWE);
     }
     if (result == ResizeResult.Bottom || result == ResizeResult.Top)
     {
         return(Cursors.SizeNS);
     }
     if (result == ResizeResult.BottomLeft || result == ResizeResult.TopRight)
     {
         return(Cursors.SizeNESW);
     }
     if (result == ResizeResult.BottomRight || result == ResizeResult.TopLeft)
     {
         return(Cursors.SizeNWSE);
     }
     return(Cursors.Default);
 }
        public async Task BasicTests()
        {
            string       tmpFile       = Path.GetTempFileName();
            FileStream   tmpFileStream = new FileStream(tmpFile, FileMode.Create);
            MemoryStream tmpStream     = new MemoryStream();

            try
            {
                var fileSystemMock = new Mock <IFileSystemHelper>();
                fileSystemMock.Setup(f => f.isDirectoryExists(It.IsAny <string>())).Returns(true);
                fileSystemMock.Setup(f => f.CreateFile(It.IsAny <string>())).Returns(tmpFileStream);

                var hostingEnvironmentMock = new Mock <IHostingEnvironment>();
                hostingEnvironmentMock.Setup(h => h.WebRootPath).Returns("x:\\tmp");

                var httpContextAccessorMock = new Mock <IHttpContextAccessor>();
                var httpContextMock         = new Mock <HttpContext>();
                httpContextAccessorMock.Setup(h => h.HttpContext).Returns(httpContextMock.Object);
                httpContextMock.Setup(h => h.Request.Host).Returns(new HostString("foo"));
                httpContextMock.Setup(h => h.Request.Scheme).Returns("https");

                var resizerMock = new Mock <IResizer>();
                resizerMock.Setup(r => r.Resize(It.IsAny <string>(), It.IsAny <int>(), It.IsAny <int>())).Returns(Task.FromResult("http://resized"));

                var localFileProvider = new LocalFileProvider(
                    hostingEnvironmentMock.Object,
                    httpContextAccessorMock.Object,
                    resizerMock.Object,
                    fileSystemMock.Object);

                ResizeResult result = await localFileProvider.Resize("foo.jpg", tmpStream);

                Assert.Equal("https://foo/dl/foo.jpg", result.UriActualSize);
                Assert.Equal("http://resized", result.UriResizedSize);
            }
            finally
            {
                tmpFileStream.Dispose();
                tmpStream.Dispose();
            }
        }
        /// <summary>
        /// Get Resized Image
        /// </summary>
        /// <param name="width">Desired with of the image - will be set to actual image width</param>
        /// <param name="height">Desired height of the image - will be set to actual image height</param>
        /// <returns></returns>
        public static ResizeResult ResizeAndFilterImage(string file, ImageFiltrationParameters parameters)
        {
            var result = new ResizeResult();

            result.Output     = new MemoryStream();
            result.SourceFile = file;

            // make sure we have no problem with file lock
            var source = File.ReadAllBytes(file);

            using (var ms = new MemoryStream(source))
                using (var b = Bitmap.FromStream(ms))
                {
                    bool isPNG  = b.RawFormat.Equals(ImageFormat.Png);
                    bool isJPEG = b.RawFormat.Equals(ImageFormat.Jpeg);

                    parameters.Validate(b);

                    Bitmap newBitMap = null;

                    #region Resize

                    if (parameters.IsProcessResize == true)
                    {
                        newBitMap = new Bitmap(parameters.TargetWidth, parameters.TargetHeight);
                        var g = Graphics.FromImage(newBitMap);

                        if (isPNG == true)
                        {
                            g.Clear(Color.Transparent);
                        }
                        else
                        {
                            g.Clear(Color.White);
                        }

                        ImageResizeModule.FillBackground(b, g, parameters);

                        g.SmoothingMode      = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                        g.InterpolationMode  = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                        g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                        g.PixelOffsetMode    = System.Drawing.Drawing2D.PixelOffsetMode.Half;

                        g.DrawImage(b, parameters.ImageOffsetAndSize.Left,
                                    parameters.ImageOffsetAndSize.Top,
                                    parameters.ImageOffsetAndSize.Width,
                                    parameters.ImageOffsetAndSize.Height);
                        g.Dispose();
                    }
                    else
                    {
                        newBitMap = (Bitmap)b;
                    }

                    #endregion

                    #region Filtration

                    if (parameters.Filters != null)
                    {
                        foreach (var filter in parameters.Filters)
                        {
                            if (filter.ToLower() == "grayscale")
                            {
                                var filtered = AForge.Imaging.Filters.Grayscale.CommonAlgorithms.Y.Apply(newBitMap);
                                newBitMap.Dispose();
                                newBitMap = filtered;
                                continue;
                            }

                            var name       = " AForge.Imaging.Filters." + filter;
                            var filterType = Assembly.GetAssembly(typeof(AForge.Imaging.Filters.BaseFilter)).GetType(name, false, true);
                            if (filterType == null ||
                                filterType.IsAbstract ||
                                filterType.IsInterface ||
                                !filterType.IsPublic)
                            {
                                throw new InvalidOperationException("Filter name " + filter + " is not valid");
                            }

                            try
                            {
                                var instance = Activator.CreateInstance(filterType) as AForge.Imaging.Filters.IFilter;
                                if (instance == null)
                                {
                                    throw new InvalidOperationException("Filter name " + filter + " is not valid");
                                }

                                var filtered = instance.Apply(newBitMap);
                                newBitMap.Dispose();
                                newBitMap = filtered;
                            }
                            catch (Exception ex)
                            {
                                throw new InvalidOperationException("Filter name " + filter + " is not valid", ex);
                            }
                        }
                    }

                    #endregion

                    if (isJPEG == true)
                    {
                        var ep = new EncoderParameters();
                        ep.Param[0] = new EncoderParameter(Encoder.Quality, 95L);

                        var ici = (from item in ImageCodecInfo.GetImageEncoders()
                                   where item.MimeType.Equals("image/jpeg", StringComparison.OrdinalIgnoreCase)
                                   select item).FirstOrDefault();

                        try
                        {
                            newBitMap.Save(result.Output, ici, ep);
                        }
                        catch (Exception)
                        {
                            newBitMap.Save(result.Output, ImageFormat.Jpeg);
                        }

                        result.ContentType = "image/jpeg";
                    }
                    else
                    {
                        result.ContentType = "image/png";
                        newBitMap.Save(result.Output, ImageFormat.Png);
                    }

                    newBitMap.Dispose();
                }

            result.Output.Position = 0;

            return(result);
        }
Beispiel #5
0
        /// <summary>
        /// Starts the form resize from edge.
        /// </summary>
        /// <param name="f">The f.</param>
        /// <param name="result">The result.</param>
        /// <param name="c">The c.</param>
        public static void StartFormResizeFromEdge(System.Windows.Forms.Form f, ResizeResult result, Control c = null)
        {
            var minimum = f is Zeroit.Framework.Form.ModernForm.Forms.ModernForm modernForm ? modernForm.MinimumSize : f.MinimumSize;
            var maximum = f is Zeroit.Framework.Form.ModernForm.Forms.ModernForm form ? form.MaximumSize : f.MaximumSize;
            //Cursor.Clip = Screen.GetWorkingArea(f);
            var curLoc     = f.PointToClient(Cursor.Position);
            var fLoc       = new Point(f.Left, f.Top);
            var w          = f.Width;
            var h          = f.Height;
            var resultEnum = ((ResizeResult)result);

            Action <Object, MouseEventArgs> mouseMove = (s, e) => {
                if (f.WindowState != FormWindowState.Maximized)
                {
                    var changedSize  = (new Size(curLoc) - new Size(e.Location)).Width;
                    var changedSizeH = (new Size(curLoc) - new Size(e.Location)).Height;
                    f.Cursor = HitTestToCursor(result);
                    switch (resultEnum)
                    {
                    case ResizeResult.Left:
                        if (curLoc.X <= Zeroit.Framework.Form.ModernForm.Forms.ModernForm.SizingBorder && ((f.Width + changedSize) >= minimum.Width))
                        {
                            f.Left  -= changedSize;
                            fLoc     = new Point(f.Left, f.Top);
                            f.Width += changedSize;
                            f.Update();
                        }
                        break;

                    case ResizeResult.Right:
                        if (curLoc.X >= minimum.Width - Zeroit.Framework.Form.ModernForm.Forms.ModernForm.SizingBorder)
                        {
                            f.Left  = fLoc.X;
                            curLoc  = f.PointToClient(Cursor.Position);
                            f.Width = w - changedSize;
                            f.Update();
                            w = f.Width;
                        }
                        break;

                    case ResizeResult.Bottom:
                        if (curLoc.Y >= minimum.Height - Zeroit.Framework.Form.ModernForm.Forms.ModernForm.SizingBorder)
                        {
                            f.Top    = fLoc.Y;
                            curLoc   = f.PointToClient(Cursor.Position);
                            f.Height = h - changedSizeH;
                            f.Update();
                            h = f.Height;
                        }
                        break;

                    case ResizeResult.BottomLeft:
                        if (curLoc.X <= Zeroit.Framework.Form.ModernForm.Forms.ModernForm.SizingBorder && curLoc.Y >= minimum.Height - Zeroit.Framework.Form.ModernForm.Forms.ModernForm.SizingBorder && ((f.Width + changedSize) >= minimum.Width))
                        {
                            var ww = e.Location.X - f.Left;
                            var hh = e.Location.Y - f.Bottom;

                            f.Height = f.Bottom + hh;
                            f.Left  -= changedSize;
                            fLoc     = new Point(f.Left, f.Top);
                            f.Width += changedSize;

                            f.Update();
                        }
                        break;

                    case ResizeResult.BottomRight:
                        var ww2 = e.Location.X - f.Right;
                        var hh2 = e.Location.Y - f.Bottom;

                        f.Height = f.Bottom + hh2;

                        fLoc     = new Point(f.Left, f.Top);
                        f.Width += f.Left + ww2;

                        f.Update();

                        break;
                    }
                }
            };
            MouseEventHandler invoke = mouseMove.Invoke;

            f.MouseMove += invoke;
            MouseEventHandler invokeCMove = (s, e) => {
                var pt = f.PointToClient(((Control)s).PointToScreen(e.Location));
                var x  = pt.X;
                var y  = pt.Y;


                invoke(f, new MouseEventArgs(e.Button, e.Clicks, x, y, e.Delta));
            };

            if (c != null)
            {
                c.MouseMove += invokeCMove;
            }



            MouseEventHandler invoke2 = null;

            invoke2 = (s, e) => {
                if (c != null)
                {
                    c.MouseMove -= invokeCMove;
                }
                if (c != null)
                {
                    c.MouseUp -= invoke2;
                }
                f.MouseUp   -= invoke2;
                f.MouseMove -= invoke;
                f.Update();
                //Cursor.Clip = new Rectangle();
            };

            f.MouseUp += invoke2;
            if (c != null)
            {
                c.MouseUp += invoke2;
            }
        }