Ejemplo n.º 1
0
        public byte[] Transform(byte[] img, TransformationParametrs parametrs)
        {
            byte[]    result;
            Rectangle cropRectangle = new Rectangle(parametrs.TopLeftConerX, parametrs.TopLeftConerY, parametrs.Width, parametrs.Height);

            if (cropRectangle.Width == 0 || cropRectangle.Height == 0)
            {
                throw new ArgumentOutOfRangeException("Пустая область");
            }
            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(img);
                    if (imageFactory.Image.Width > 1000 || imageFactory.Image.Height > 1000)
                    {
                        throw new ArgumentException("Слишком большое изображение");
                    }
                    if (parametrs.Flip != Flip.None)
                    {
                        if (parametrs.Flip == Flip.Horizontal)
                        {
                            imageFactory.Flip(false);
                        }
                        else
                        {
                            imageFactory.Flip(true);
                        }
                    }
                    if (parametrs.Rotation != Rotation.None)
                    {
                        if (parametrs.Rotation == Rotation.Clockwise)
                        {
                            imageFactory.Rotate(90);
                        }
                        else
                        {
                            imageFactory.Rotate(-90);
                        }
                    }
                    try
                    {
                        imageFactory.Crop(cropRectangle);
                    }
                    catch (ArgumentOutOfRangeException)
                    {
                        throw new ArgumentOutOfRangeException("Пустая область");
                    }
                    imageFactory.Save(outStream);
                }

                // Do something with the stream.
                result = outStream.ToArray();
            }

            return(result);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Flips the image.
        /// </summary>
        /// <param name="isVerticalFlip">Is vertical flip?</param>
        /// <returns>The resulting image.</returns>
        public Image FlipImage(bool isVerticalFlip)
        {
            _editor.Flip(isVerticalFlip);
            SaveToTempImage();

            return(_editor.Image);
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Performs the Flip effect from the ImageProcessor library.
        /// </summary>
        /// <param name="image">The image with which to apply the effect.</param>
        /// <param name="verticalFlip">Determines if the flip should be vertical or horizontal.</param>
        /// <returns>A new image with the effect applied.</returns>
        public Image Flip(Image image, bool verticalFlip)
        {
            using var factory = new ImageFactory();

            factory.Load(image);
            factory.Flip(verticalFlip);

            var result = factory.Image;

            return(new Bitmap(result));
        }
Ejemplo n.º 4
0
        void IModule.Install(ModuleManager manager)
        {
            _manager = manager;
            _client  = manager.Client;
            _http    = _client.GetService <HttpService>();

            manager.CreateCommands("image", group =>
            {
                group.CreateCommand("caption")
                .Parameter("uri", ParameterType.Required)
                .Parameter("parameters", ParameterType.Unparsed)
                .Description("Adds text to an Image.\n<`uri`> ⦗`color`⦘ ⦗`alpha`⦘ ⦗`position`⦘ ⦗`fontsize`⦘ ⦗`dropshadow`⦘\nExample usage:\n⦗`cap http://myimage.png red 0.5 center arial 12 1 hello world`⦘\n⦗`cap http://myimage.png hello world`⦘")
                .Alias("cap")
                .Do(async e =>
                {
                    if (e.Args.Any())
                    {
                        var args   = getArgs(e);
                        string uri = e.Args[0];

                        if (args.Any())
                        {
                            if (await isImage(uri))
                            {
                                string file = "img_cap_tmp" + Guid.NewGuid().ToString() + await getImageExtension(uri);

                                try
                                {
                                    await DownloadImage(uri, file);
                                }
                                catch (WebException ex)
                                {
                                    await _client.ReplyError(e, ex.Message);
                                    _client.Log.Error("captions", ex);

                                    if (File.Exists(file))
                                    {
                                        File.Delete(file);
                                    }
                                    return;
                                }

                                if (File.Exists(file))
                                {
                                    byte[] pb = File.ReadAllBytes(file);

                                    var asd        = new TextLayer();
                                    asd.Text       = args?["text"];
                                    asd.FontColor  = args.ContainsKey("color") ? System.Drawing.Color.FromName(args["color"]) : System.Drawing.Color.White;
                                    asd.FontFamily = args.ContainsKey("font") ? FontFamily.Families.Where(x => x.Name == args["font"]).FirstOrDefault() : FontFamily.GenericSerif;
                                    asd.DropShadow = args.ContainsKey("dropshadow") ? bool.Parse(args["dropshadow"]) : false;
                                    // asd.Position = Point.Empty;
                                    asd.Opacity  = args.ContainsKey("opacity") ? int.Parse(args["opacity"]) : 100;
                                    asd.Style    = args.ContainsKey("style") ? (FontStyle)Enum.Parse(typeof(FontStyle), args["style"], true) : FontStyle.Regular;
                                    asd.FontSize = args.ContainsKey("size") ? int.Parse(args["size"]) : 20;

                                    ISupportedImageFormat format = new PngFormat {
                                        Quality = 100
                                    };

                                    using (MemoryStream ins = new MemoryStream(pb))
                                        using (MemoryStream outs = new MemoryStream())
                                            using (ImageFactory iff = new ImageFactory(true))
                                            {
                                                iff.Load(ins)
                                                .Watermark(asd)
                                                .Format(format)
                                                .Save(outs);
                                                await e.Channel.SendFile("output.png", outs);
                                            }
                                    File.Delete(file);
                                }
                                else
                                {
                                    await _client.ReplyError(e, "Couldn't find your image on my end. Bug @Techbot about it.");
                                    return;
                                }
                            }
                            else
                            {
                                await _client.ReplyError(e, "That doesn't seem to be an image...");
                            }
                        }
                        else
                        {
                            await _client.ReplyError(e, "No Parameters provided, aborting...");
                            return;
                        }
                    }
                    else
                    {
                        await _client.Reply(e, "Usage: `cap [link] <text>`");
                    }
                });
                group.CreateCommand("edit")
                .Parameter("uri", ParameterType.Required)
                .Parameter("parameters", ParameterType.Unparsed)
                .Description("transforms an image.\nSupported Parameters:\n\n\nTint: `tint=red`\nCensor: `censor=x;y;w;h`\n`Scaling: `w=num or h=num`\n`blur=num`\n`rot=num`\n`filp=true/false`\n`crop=true + (top=num or bottom=num or left=num or right=num)`")
                .Alias("e")
                .Do(async e =>
                {
                    if (e.Args.Any())
                    {
                        var args   = getArgs(e);
                        string uri = e.Args[0];

                        if (await isImage(uri))
                        {
                            string file = "img_e_tmp" + Guid.NewGuid().ToString() + await getImageExtension(uri);
                            try
                            {
                                await DownloadImage(uri, file);
                            }
                            catch (WebException ex)
                            {
                                await _client.ReplyError(e, ex.Message);
                                _client.Log.Error("captions", ex);

                                if (File.Exists(file))
                                {
                                    File.Delete(file);
                                }
                                return;
                            }
                            if (File.Exists(file))
                            {
                                byte[] pb = File.ReadAllBytes(file);

                                ISupportedImageFormat format = new PngFormat {
                                    Quality = 100
                                };

                                using (MemoryStream ins = new MemoryStream(pb))
                                    using (MemoryStream outs = new MemoryStream())
                                        using (ImageFactory iff = new ImageFactory(true))
                                        {
                                            iff.Load(ins);
                                            if (args.ContainsKey("rot"))
                                            {
                                                iff.Rotate(int.Parse(args["rot"]));
                                            }
                                            if (args.ContainsKey("flip"))
                                            {
                                                iff.Flip(bool.Parse(args["flip"]));
                                            }
                                            if (args.ContainsKey("blur"))
                                            {
                                                iff.GaussianBlur(int.Parse(args["blur"]));
                                            }
                                            if (args.ContainsKey("ecrop"))
                                            {
                                                iff.EntropyCrop(byte.Parse(args["ecrop"]));
                                            }
                                            if (args.ContainsKey("pixelate"))
                                            {
                                                iff.Pixelate(int.Parse(args["pixelate"]));
                                            }
                                            if (args.ContainsKey("tint"))
                                            {
                                                iff.Tint(System.Drawing.Color.FromName(args["tint"]));
                                            }
                                            if (args.ContainsKey("replacecolor"))
                                            {
                                                string[] rcargs          = args["replacecolor"].Split(';');
                                                System.Drawing.Color tar = System.Drawing.Color.FromName(rcargs[0]);
                                                System.Drawing.Color rep = System.Drawing.Color.FromName(rcargs[1]);

                                                if (rcargs.Length > 2 && int.Parse(rcargs[2]) >= 128 || int.Parse(rcargs[2]) < 0)
                                                {
                                                    await _client.ReplyError(e, "Fuzzines mix and max values are 0 - 128");
                                                    File.Delete(file);
                                                    return;
                                                }
                                                int fuzz = rcargs.Length > 2 ? int.Parse(rcargs[2]) : 128;

                                                iff.ReplaceColor(tar, rep, fuzz);
                                            }
                                            if (args.ContainsKey("censor"))
                                            {
                                                string[] cargs = args["censor"].Split(';');
                                                var pixels     = int.Parse(cargs[4]);
                                                var x          = int.Parse(cargs[0]);
                                                var y          = -int.Parse(cargs[1]);
                                                var w          = int.Parse(cargs[2]);
                                                var h          = int.Parse(cargs[3]);

                                                iff.Pixelate(pixels, new Rectangle(new Point(x, y), new Size(w, h)));
                                            }
                                            if (args.ContainsKey("w") || args.ContainsKey("h"))
                                            {
                                                int width = 0, height = 0;

                                                if (args.ContainsKey("w"))
                                                {
                                                    width = int.Parse(args["w"]);
                                                }

                                                if (args.ContainsKey("h"))
                                                {
                                                    height = int.Parse(args["h"]);
                                                }
                                                iff.Resize(new ResizeLayer(new Size(width, height), ResizeMode.Stretch, AnchorPosition.Center, true, null, new Size(5000, 5000)));
                                            }
                                            if (args.ContainsKey("crop"))
                                            {
                                                int top = 0, bottom = 0, left = 0, right = 0;

                                                // is there a better way to do this?

                                                if (args.ContainsKey("top"))
                                                {
                                                    top = int.Parse(args["top"]);
                                                }
                                                if (args.ContainsKey("bottom"))
                                                {
                                                    bottom = int.Parse(args["bottom"]);
                                                }
                                                if (args.ContainsKey("left"))
                                                {
                                                    left = int.Parse(args["left"]);
                                                }
                                                if (args.ContainsKey("right"))
                                                {
                                                    right = int.Parse(args["right"]);
                                                }

                                                iff.Crop(new CropLayer(
                                                             top,
                                                             bottom,
                                                             left,
                                                             right,
                                                             CropMode.Percentage));
                                            }

                                            iff
                                            .Format(format)
                                            .Save(outs);
                                            await e.Channel.SendFile("output.png", outs);
                                        }
                                File.Delete(file);
                            }
                            else
                            {
                                await _client.ReplyError(e, "Couldn't find your image on my end. Bug @Techbot about it.");
                                return;
                            }
                        }
                        else
                        {
                            await _client.ReplyError(e, "That doesn't seem to be an image...");
                        }
                    }
                });
            });
        }
Ejemplo n.º 5
0
 public ImageFactory PerformAction(ImageFactory image)
 {
     return(image.Flip(this.FlipVertical));
 }
Ejemplo n.º 6
0
 protected override ImageFactory transform(ImageFactory factory)
 {
     return(factory.Flip(flipVertically));
 }
Ejemplo n.º 7
0
 public IImageTransformer Flip(bool flipVertically = false, bool flipBoth = false)
 {
     _image.Flip(flipVertically, flipBoth);
     return(this);
 }
Ejemplo n.º 8
0
        public static void Process(ref byte[] buffer, Dictionary <string, double> edits)
        {
            using (var inputStream = new MemoryStream(buffer))
            {
                using (var outputStream = new MemoryStream())
                {
                    using (var factory = new ImageFactory())
                    {
                        factory.Load(inputStream);

                        foreach (var edit in edits)
                        {
                            switch (edit.Key)
                            {
                            case "Alpha":
                            {
                                factory.Alpha((int)edit.Value);
                                break;
                            }

                            case "Contrast":
                            {
                                factory.Contrast((int)edit.Value);
                                break;
                            }

                            case "Exposure":
                            {
                                factory.Brightness((int)edit.Value);
                                break;
                            }

                            case "Flip":
                            {
                                var flipVertical = edit.Value == 1;
                                factory.Flip(flipVertical);
                                break;
                            }

                            case "Pixelate":
                            {
                                factory.Pixelate((int)edit.Value);
                                break;
                            }

                            case "Quality":
                            {
                                factory.Quality((int)edit.Value);
                                break;
                            }

                            case "Rotate":
                            {
                                factory.Rotate((int)edit.Value);
                                break;
                            }

                            case "Rounded":
                            {
                                factory.RoundedCorners((int)edit.Value);
                                break;
                            }

                            case "Saturation":
                            {
                                factory.Saturation((int)edit.Value);
                                break;
                            }
                            }
                        }

                        factory.Save(outputStream);

                        var length = (int)outputStream.Length;

                        buffer = new byte[length];

                        outputStream.Read(buffer, 0, length);
                    }
                }
            }
        }
Ejemplo n.º 9
0
 public override void Apply(ImageFactory fs)
 {
     fs = fs.Flip(vertical);
 }
Ejemplo n.º 10
0
 public void FlipMe(bool horizontal, bool both = false)
 {
     this.Reset();
     imFactory.Flip(horizontal, both);
 }
Ejemplo n.º 11
0
 /// <summary>
 /// Flips an image
 /// </summary>
 /// <param name="pImage"></param>
 /// <param name="flipVertical"></param>
 /// <param name="flipHorizontal"></param>
 /// <returns></returns>
 public Image FlipImage(Image pImage, bool flipVertical, bool flipHorizontal)
 {
     _imageFactory.Load(pImage);
     _imageFactory.Flip(flipVertical, flipHorizontal);
     return(_imageFactory.Image);
 }
Ejemplo n.º 12
0
        private static void ApplyFilterSetting(ImageFactory imageToAdjust, string setting, string value)
        {
            switch (setting)
            {
            case "brightness":
                imageToAdjust.Brightness(int.Parse(value));
                break;

            case "contrast":
                imageToAdjust.Contrast(int.Parse(value));
                break;

            case "filter":
                switch (value)
                {
                case "gotham":
                    imageToAdjust.Filter(MatrixFilters.Gotham);
                    break;

                case "invert":
                    imageToAdjust.Filter(MatrixFilters.Invert);
                    break;

                case "polaroid":
                    imageToAdjust.Filter(MatrixFilters.Polaroid);
                    break;

                case "blackwhite":
                    imageToAdjust.Filter(MatrixFilters.BlackWhite);
                    break;

                case "greyscale":
                    imageToAdjust.Filter(MatrixFilters.GreyScale);
                    break;

                case "lomograph":
                    imageToAdjust.Filter(MatrixFilters.Lomograph);
                    break;

                case "sepia":
                    imageToAdjust.Filter(MatrixFilters.Sepia);
                    break;

                case "comic":
                    imageToAdjust.Filter(MatrixFilters.Comic);
                    break;

                case "hisatch":
                    imageToAdjust.Filter(MatrixFilters.HiSatch);
                    break;

                case "losatch":
                    imageToAdjust.Filter(MatrixFilters.LoSatch);
                    break;
                }

                break;

            case "flip":
                imageToAdjust.Flip(flipVertically: value == "vertical", flipBoth: value == "both");
                break;

            case "rotate":
                imageToAdjust.Rotate(int.Parse(value));
                break;
            }
        }