Ejemplo n.º 1
0
 public override MagickImage CompositeLayers()
 {
     using (var main = GetMainLayer())
         using (var emission = GetEmissionLayer())
         {
             var(width, height) = DecideCompositionSize(main, emission);
             var newImage = new MagickImage(MagickColors.Black, width, height);
             using (var mainImage = main.GetMagickImage())
             {
                 mainImage.HasAlpha = false;
                 mainImage.Resize(width, height);
                 newImage.Composite(mainImage, CompositeOperator.Plus);
             }
             if (HasEmission())
             {
                 using (var emissionImage = emission.GetMagickImage())
                 {
                     emissionImage.Resize(width, height);
                     emissionImage.HasAlpha = false;
                     newImage.Composite(emissionImage, CompositeOperator.Screen);
                 }
             }
             if (main.image != null && main.image.HasAlpha)
             {
                 newImage.HasAlpha = true;
                 newImage.CopyPixels(main.image, Channels.Alpha);
             }
             return(newImage);
         }
 }
Ejemplo n.º 2
0
        private string Process()
        {
            try
            {
                using (MagickImage srcMagickImage = new MagickImage(_inputFilePath))
                {
                    using (MagickImage grayScaleImage = (MagickImage)srcMagickImage.Clone())
                    {
                        using (MagickImage beforeImage = new MagickImage(new MagickColor(160, 160, 160, 255), srcMagickImage.Width, srcMagickImage.Height))
                        {
                            using (MagickImage afterImage = new MagickImage(new MagickColor(56, 56, 56, 255), srcMagickImage.Width, srcMagickImage.Height))
                            {
                                grayScaleImage.Grayscale(PixelIntensityMethod.Undefined);
                                grayScaleImage.BrightnessContrast(new Percentage(10), new Percentage(10));

                                grayScaleImage.Composite(beforeImage, CompositeOperator.SoftLight);
                                grayScaleImage.Composite(afterImage, CompositeOperator.Lighten);
                                grayScaleImage.Write(_outputFilePath);

                                return(string.Empty);
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                return(e.Message);
            }
        }
Ejemplo n.º 3
0
        // @TODO: Eventually use distort overlay instead, for increased precision.
        private void CreateOverlays(Geometry cropGeo, Geometry trueCropGeo)
        {
            var cropRect     = cropGeo.ToRectangle();
            var trueCropRect = trueCropGeo.ToRectangle();

            _ScreenOverlay    = new MagickImage(SCREEN_COLOR, cropRect.Width, cropRect.Height);
            _WatchZoneOverlay = new MagickImage(MagickColors.Transparent, trueCropRect.Width, trueCropRect.Height);

            if (_CompiledFeatures != null)
            {
                foreach (var wz in _CompiledFeatures.CWatchZones)
                {
                    var wzg  = wz.Geometry;
                    var wzmg = wzg.ToMagick();
                    using (var wzmi = new MagickImage(WATCHZONE_COLOR, wzmg.Width, wzmg.Height))
                        using (var wzmia = new MagickImage(MagickColors.Transparent, wzmg.Width, wzmg.Height))
                        {
                            var xOffsetWZ = (int)Math.Round(wzg.X - trueCropGeo.X);
                            var yOffsetWZ = (int)Math.Round(wzg.Y - trueCropGeo.Y);
                            var xOffsetS  = (int)Math.Round(wzg.X - cropGeo.X);
                            var yOffsetS  = (int)Math.Round(wzg.Y - cropGeo.Y);
                            _WatchZoneOverlay.Composite(wzmi, xOffsetWZ, yOffsetWZ, CompositeOperator.Over);
                            _ScreenOverlay.Composite(wzmia, xOffsetS, yOffsetS, CompositeOperator.Copy);
                        }
                }
                var xOffset = (int)Math.Round(trueCropGeo.X - cropGeo.X);
                var yOffset = (int)Math.Round(trueCropGeo.Y - cropGeo.Y);
                _ScreenOverlay.Composite(_WatchZoneOverlay, xOffset, yOffset, CompositeOperator.Over);
            }
        }
Ejemplo n.º 4
0
        public static MagickImage PerlinNoise(int width, int height)
        {
            using var noise1 = new MagickImage(MagickColors.Black, width / 160, height / 160);
            using var noise2 = new MagickImage(MagickColors.Black, width / 80, height / 80);
            using var noise3 = new MagickImage(MagickColors.Black, width / 40, height / 40);
            using var noise4 = new MagickImage(MagickColors.Black, width / 20, height / 20);
            using var noise5 = new MagickImage(MagickColors.Black, width / 10, height / 10);
            using var noise6 = new MagickImage(MagickColors.Black, width / 1, height / 1);

            noise1.AddNoise(NoiseType.Random);
            noise2.AddNoise(NoiseType.Random);
            noise3.AddNoise(NoiseType.Random);
            noise4.AddNoise(NoiseType.Random);
            noise5.AddNoise(NoiseType.Random);

            noise1.VirtualPixelMethod = VirtualPixelMethod.Tile;
            noise2.VirtualPixelMethod = VirtualPixelMethod.Tile;
            noise3.VirtualPixelMethod = VirtualPixelMethod.Tile;
            noise4.VirtualPixelMethod = VirtualPixelMethod.Tile;
            noise5.VirtualPixelMethod = VirtualPixelMethod.Tile;
            noise6.VirtualPixelMethod = VirtualPixelMethod.Tile;

            var geometry = new MagickGeometry(width, height)
            {
                FillArea = true
            };

            noise1.Evaluate(Channels.Default, EvaluateOperator.Multiply, 0.5);
            noise1.Evaluate(Channels.Default, EvaluateOperator.Add, 0.25);
            noise1.Resize(geometry);

            noise2.Evaluate(Channels.Default, EvaluateOperator.Multiply, 0.25);
            noise2.Evaluate(Channels.Default, EvaluateOperator.Add, 0.375);
            noise2.Resize(geometry);

            noise3.Evaluate(Channels.Default, EvaluateOperator.Multiply, 0.125);
            noise3.Evaluate(Channels.Default, EvaluateOperator.Add, 0.4375);
            noise3.Resize(geometry);

            noise4.Evaluate(Channels.Default, EvaluateOperator.Multiply, 0.0625);
            noise4.Evaluate(Channels.Default, EvaluateOperator.Add, 0.46875);
            noise4.Resize(geometry);

            noise5.Evaluate(Channels.Default, EvaluateOperator.Multiply, 0.03125);
            noise5.Evaluate(Channels.Default, EvaluateOperator.Add, 0.484375);
            noise5.Resize(geometry);

            noise6.Evaluate(Channels.Default, EvaluateOperator.Multiply, 0.015625);
            noise6.Evaluate(Channels.Default, EvaluateOperator.Add, 0.49921875);
            noise6.Resize(geometry);

            noise1.Composite(noise2, CompositeOperator.Plus);
            noise1.Composite(noise3, CompositeOperator.Plus);
            noise1.Composite(noise4, CompositeOperator.Plus);
            noise1.Composite(noise5, CompositeOperator.Plus);
            noise1.Composite(noise6, CompositeOperator.Plus);
            noise1.AutoLevel();

            return((MagickImage)noise1.Clone());
        }
Ejemplo n.º 5
0
        public void Process()
        {
            using (var bg = new MagickImage(MagickColor.FromRgba(255, 255, 255, 255), width, height))
            {
                using (var image = new MagickImage(input))
                {
                    if (image.HasAlpha == false)
                    {
                        image.Alpha(AlphaOption.Opaque);
                    }
                    using (var cover = image.Clone())
                    {
                        MagickGeometry resize = new MagickGeometry(width + "x" + height + "^");
                        image.Resize(resize);
                        image.Extent(width, height, Gravity.Center);
                        image.Blur(80, 30);

                        bg.Composite(image, 0, 0, CompositeOperator.Over);

                        MagickGeometry centerResize = new MagickGeometry(height * 0.7 + "x" + height * 0.7);
                        cover.Resize(centerResize);
                        using (var coverShadow = cover.Clone())
                        {
                            coverShadow.BackgroundColor = MagickColor.FromRgba(192, 192, 192, 192);
                            coverShadow.Shadow(50, 50, 10, new Percentage(90));

                            bg.Composite(coverShadow, Gravity.Center, CompositeOperator.Over);
                        }

                        bg.Composite(cover, Gravity.Center, CompositeOperator.Over);
                    }
                }
                bg.Write(output);
            }
        }
Ejemplo n.º 6
0
        private string Process()
        {
            try
            {
                using (MagickImage srcMagickImage = new MagickImage(_inputFilePath))
                {
                    using (MagickImage sepiaImage = new MagickImage(new MagickColor(125, 125, 125, 60), srcMagickImage.Width, srcMagickImage.Height))
                    {
                        sepiaImage.SepiaTone(new Percentage(80));

                        sepiaImage.Composite(srcMagickImage, CompositeOperator.Overlay);

                        sepiaImage.BrightnessContrast(new Percentage(0), new Percentage(10));
                        sepiaImage.Modulate(new Percentage(100), new Percentage(100), new Percentage(100));

                        using (MagickImage beforeImage = new MagickImage(new MagickColor(247, 176, 15, 25), srcMagickImage.Width, srcMagickImage.Height))
                        {
                            using (MagickImage afterImage = new MagickImage(new MagickColor(0, 70, 150, 120), srcMagickImage.Width, srcMagickImage.Height))
                            {
                                sepiaImage.Composite(beforeImage, CompositeOperator.Darken);

                                sepiaImage.Composite(afterImage, CompositeOperator.Lighten);
                                sepiaImage.Write(_outputFilePath);

                                return(string.Empty);
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                return(e.Message);
            }
        }
Ejemplo n.º 7
0
        public static void GenerateLogo(
            System.Drawing.Color textFillColor,
            System.Drawing.Color borderColor,
            System.Drawing.Color backgroundColor,
            System.Drawing.Color strokeColor,
            System.Drawing.Color shadowColor,
            System.Drawing.Color BackgroundShadow,
            int strokeWidth         = 1,
            bool caption            = true,
            int borderSize          = 4,
            bool border             = true,
            bool BackgroundShadowOn = true,
            string textDesc         = "Long game adventure test",
            string fontName         = @"C:\Windows\Fonts\comicbd.ttf")
        {
            using (var magick = new MagickImage(backgroundColor, 400, 175))
            {
                if (border)
                {
                    using (var borderimage = new MagickImage(new MagickColor(), 400 - 8, 175 - 8))
                    {
                        borderimage.BorderColor = borderColor;
                        borderimage.Border(borderSize);
                        borderimage.Emboss();
                        borderimage.RePage();

                        magick.Composite(borderimage, CompositeOperator.Atop);
                    }

                    if (BackgroundShadowOn)
                    {
                        var clone = AddShadow(magick);
                    }
                }

                var textToWrite = "";
                if (caption)
                {
                    textToWrite = "caption: " + textDesc;
                }
                else
                {
                    textToWrite = "label: " + textDesc;
                }

                using (var textImage = new MagickImage())
                {
                    CreateText(textImage, textToWrite, caption, textFillColor);

                    magick.Composite(textImage, Gravity.Center, CompositeOperator.Over);
                }


                magick.Write("preview.png");
            }
        }
Ejemplo n.º 8
0
        public void Haah()
        {
            MagickImage clone = new MagickImage(image);

            clone.Flip();
            clone.Extent(clone.Width, clone.Height / 2);
            image.Composite(clone, CompositeOperator.Over);

            clone.Dispose();
        }
Ejemplo n.º 9
0
        private string Process()
        {
            try
            {
                using (MagickImage srcMagickImage = new MagickImage(_inputFilePath))
                {
                    using (MagickImage sepiaImage = new MagickImage(new MagickColor(125, 125, 125, 55), srcMagickImage.Width, srcMagickImage.Height))
                    {
                        sepiaImage.SepiaTone(new Percentage(92));
                        sepiaImage.Composite(srcMagickImage, CompositeOperator.Overlay);
                        sepiaImage.BrightnessContrast(new Percentage(10), new Percentage(0));

                        using (Bitmap bitmap = new Bitmap(srcMagickImage.Width * 2, srcMagickImage.Height * 2))
                        {
                            using (Graphics graphics = Graphics.FromImage(bitmap))
                            {
                                Rectangle    rectangle = new Rectangle(0, 0, srcMagickImage.Width * 2, srcMagickImage.Height * 2);
                                GraphicsPath gp        = new GraphicsPath();
                                gp.AddEllipse(rectangle);

                                PathGradientBrush pgb = new PathGradientBrush(gp)
                                {
                                    CenterPoint    = new PointF(rectangle.Width / 2, rectangle.Height / 2),
                                    CenterColor    = Color.White,
                                    SurroundColors = new Color[] { new MagickColor(0, 0, 0, 200) }
                                };


                                graphics.FillPath(pgb, gp);

                                bitmap.Save("gradientImage.jpg", ImageFormat.Jpeg);

                                pgb.Dispose();
                                gp.Dispose();
                            }
                        }

                        using (MagickImage afterImage = new MagickImage("gradientImage.jpg"))
                        {
                            afterImage.Crop(afterImage.Width / 4, afterImage.Height / 4, afterImage.Width / 2, afterImage.Height / 2);

                            sepiaImage.Composite(afterImage, CompositeOperator.ColorBurn);
                            sepiaImage.Write(_outputFilePath);
                            sepiaImage.Dispose();

                            return(string.Empty);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                return(e.Message);
            }
        }
Ejemplo n.º 10
0
        public void MakeCards()
        {
            var deck = JsonConvert.DeserializeObject<Deck>(File.ReadAllText(@"C:\temp\testdeck.cm"));

            var cards = new List<MagickImage>();
            foreach (var card in deck.Cards) {
                var image = new MagickImage(new MagickColor("WhiteSmoke"), deck.Width, deck.Height);
                image.Density = new MagickGeometry(300, 300);
                image.Format = MagickFormat.Bmp;
                foreach (var element in deck.Elements) {
                    var data = card.ElementData[element.Key];
                    if (File.Exists(data)) {
                        using (var overlayImage = new MagickImage(data)) {
                            image.Composite(overlayImage, (int)element.Value.X, (int)element.Value.Y, CompositeOperator.Over);
                        }
                    } else {
                        using (var textImage = new MagickImage(MagickColor.Transparent, deck.Width, deck.Height)) {
                            textImage.Density = new MagickGeometry(300, 300);
                            textImage.Font = "Arial";
                            textImage.FontPointsize = 12;
                            textImage.FillColor = new MagickColor("Black");
                            var drawableText = new DrawableText(element.Value.X, element.Value.Y, data);
                            textImage.Draw(drawableText);
                            image.Composite(textImage, CompositeOperator.Over);
                        }
                    }
                }
                image.Write(string.Format(@"c:\temp\CardMaker\{0}.png", card.Name));
                cards.Add(image);

            }
            using (var doc = new Document()) {
                PdfWriter.GetInstance(doc, new FileStream(@"C:\temp\CardMaker\cards.pdf", FileMode.Create));
                doc.Open();
                var columns = (int)Math.Floor(doc.PageSize.Width / (deck.Width + 10));
                var table = new PdfPTable(columns) { WidthPercentage = 100, DefaultCell = { Border = 0, Padding = 5 } };

                foreach (var card in cards) {
                    var instance = Image.GetInstance(card.ToByteArray());
                    instance.SetDpi(300, 300);
                    var cell = new PdfPCell(instance) {
                        HorizontalAlignment = Element.ALIGN_CENTER,
                        Border = 0,
                        Padding = 5,
                    };
                    table.AddCell(cell);
                }
                table.CompleteRow();
                doc.Add(table);
            }
        }
Ejemplo n.º 11
0
        public static BitmapImage Compose(this Project project)
        {
            var width  = project.size.width;
            var height = project.size.height;
            var layers = project.layers.ToList();

            using var final = new MagickImage(MagickColors.Transparent, width, height);
            // final.Settings.Format = MagickFormat.Bmp;

            // for (int i = 0; i < project.layers.Count; i++) {
            for (int i = project.layers.Count - 1; i >= 0; i--)
            {
                var layer = project.layers[i];

                // If the layer is hidden, do not draw it.
                if (layer.visible == false)
                {
                    continue;
                }

                // If this is the base layer don't apply a composite.
                var blend    = layer.blendType;
                var isBottom = IsBottomLayer(layer, layers);
                if (isBottom)
                {
                    blend = CompositeOperator.SrcOver;
                }

                // Get the position of where the image should be drawn.
                var x          = layer.transform.Position.x;
                var y          = layer.transform.Position.y;
                var isAnchored = layer.transform.IsAnchored;
                var anchor     = layer.transform.Anchor;

                using var filter = layer.FilteredImage.Clone();
                try {
                    if (isAnchored)
                    {
                        final.Composite(filter, anchor, blend, Channels.RGB);
                    }
                    else
                    {
                        final.Composite(filter, x, y, blend, Channels.RGB);
                    }
                } catch { }
            }

            return(final.ToBitmapImage());
        }
Ejemplo n.º 12
0
        public MagickImage CreateSpriteSheet(SpriteSheet spriteSheet)
        {
            var result = new MagickImage(MagickColors.Transparent, spriteSheet.TotalWidth, spriteSheet.TotalHeight);

            var currentYOffset = 0;

            foreach (var animation in spriteSheet.Animations)
            {
                var currentXOffset = 0;
                foreach (var frame in animation.Frames)
                {
                    using (var tmpImage = frame.SourceImage.Clone())
                    {
                        tmpImage.Resize(new Percentage(frame.Scale * 100));
                        int imgOffsetX = frame.OffsetX < 0 ? -frame.OffsetX : 0;
                        int imgOffsetY = frame.OffsetY < 0 ? -frame.OffsetY : 0;

                        tmpImage.Crop(new MagickGeometry(imgOffsetX, imgOffsetY, frame.FrameWidth, frame.FrameHeight));
                        tmpImage.RePage();

                        result.Composite(tmpImage, currentXOffset + Math.Max(0, frame.OffsetX), currentYOffset + Math.Max(0, frame.OffsetY), CompositeOperator.Copy);
                    }
                    currentXOffset += frame.FrameWidth;
                }
                currentYOffset += animation.TotalHeight;
            }

            return(result);
        }
Ejemplo n.º 13
0
 static MagickImage Interpolate(MagickImage imageA, MagickImage imageB, double alpha)
 {
     if (alpha >= 1 || alpha <= 0)
     {
         return(null);
     }
     try
     {
         imageB.HasAlpha = true;
         imageB.Evaluate(Channels.Alpha, EvaluateOperator.Multiply, alpha);
         imageA.Composite(imageB, CompositeOperator.Over);
         MagickImage result;
         using (MemoryStream memoryStream = new MemoryStream())
         {
             imageA.Write(memoryStream, MagickFormat.Png32);
             ImageOptimizer optimizer = new ImageOptimizer();
             //optimizer.OptimalCompression = false;
             memoryStream.Position = 0;
             //optimizer.LosslessCompress(memoryStream);
             //FileStream fileStream = new FileStream(destinationPath, FileMode.Create);
             //memoryStream.WriteTo(fileStream);
             result = new MagickImage(memoryStream);
         }
         return(result);
     }
     catch (Exception ex)
     {
         return(null);
     }
 }
Ejemplo n.º 14
0
        static Tuple <bool, string> Interpolate(MagickImage imageA, MagickImage imageB, string destinationPath, double alpha)
        {
            if (alpha >= 1 || alpha <= 0)
            {
                return(new Tuple <bool, string>(false, "Alpha value must be less than 1.0 and more than 0.0"));
            }
            try
            {
                imageB.HasAlpha = true;
                imageB.Evaluate(Channels.Alpha, EvaluateOperator.Multiply, alpha);
                imageA.Composite(imageB, CompositeOperator.Over);

                using (MemoryStream memoryStream = new MemoryStream())
                {
                    imageA.Write(memoryStream, MagickFormat.Png32);
                    ImageOptimizer optimizer = new ImageOptimizer();
                    optimizer.OptimalCompression = true;
                    memoryStream.Position        = 0;
                    optimizer.LosslessCompress(memoryStream);
                    FileStream fileStream = new FileStream(destinationPath, FileMode.Create);
                    memoryStream.WriteTo(fileStream);
                }
                //imageA.Write(destinationPath, MagickFormat.Png24);
            }
            catch (Exception ex)
            {
                return(new Tuple <bool, string>(false, ex.Message));
            }
            return(new Tuple <bool, string>(true, "Success"));
        }
Ejemplo n.º 15
0
        public async Task Warm(SocketUser user = null, [Remainder] string input = "")
        {
            if (user == null)
            {
                await BetterReplyAsync("You must provide a user to warm.", parameters : $"user null; {input}");

                return;
            }

            await Context.Channel.TriggerTypingAsync();

            try {
                Task <MemoryStream> download = Http.GetStreamAsync(user.GetAvatarUrl(ImageFormat.Png, 256));
                using MemoryStream data = await download;

                if (download.IsCompletedSuccessfully)
                {
                    using MemoryStream stream = new MemoryStream(256);
                    using MagickImage image   = new MagickImage(Cache.GetStream("warm.png"));
                    using MagickImage avatar  = new MagickImage(data)
                          {
                              BackgroundColor = new MagickColor(0, 0, 0, 0)
                          };

                    avatar.Resize(225, 225);
                    avatar.Rotate(-5.5);

                    image.Composite(avatar, 160, 132, CompositeOperator.Atop);

                    image.Resize(256, 256);
                    image.Write(stream, MagickFormat.Png);

                    stream.Seek(0, SeekOrigin.Begin);

                    await BetterSendFileAsync(stream, "warm.png", $"{BetterUserFormat(user)} has been warmed{(string.IsNullOrWhiteSpace(input) ? "" : $" for `{input}`")}.", parameters : $"{user} ({user.Id}); {input}");
Ejemplo n.º 16
0
        private void MergeImage(string phase, string[] words)
        {
            var position = 1;

            using (MagickImageCollection images = new MagickImageCollection())
            {
                foreach (var line in words)
                {
                    foreach (var word in line)
                    {
                        MagickImage image = new MagickImage($"~/Words/{word}/{word}-{phase}.png");
                        //image.Extent(90, 400, position == 1 ? Gravity.Center : Gravity.South);
                        image.Extent(-5, -90 * position, 90, 400);
                        //image.Resize(500, 350);
                        image.Transparent(new MagickColor("#ffffff"));
                        images.Add(image);
                    }

                    position++;
                }

                using (MagickImage horizontal = images.AppendHorizontally())
                {
                    MagickImage background = new MagickImage("~/Words/background.png");
                    horizontal.Composite(background, CompositeOperator.DstAtop);

                    Directory.CreateDirectory($"{OutputPath}/{FolderName}");
                    horizontal.Write($"{OutputPath}/{FolderName}/{FolderName}-{phase}.png");
                    background.Dispose();
                }
            }
        }
Ejemplo n.º 17
0
        private void crop_images()
        {
            foreach (var s in sheet.sprites)
            {
                using (MagickImage image_a = new MagickImage(alphaPath))
                {
                    using (MagickImage image_rgb = new MagickImage(rgbPath))
                    {
                        var g = new ImageMagick.MagickGeometry(s.x, s.y, s.w, s.h);
                        image_a.Crop(g);

                        image_rgb.Crop(g);
                        image_rgb.Composite(image_a, CompositeOperator.CopyAlpha);
                        int i = 1;
                        while (i < Math.Max(s.w, s.h))
                        {
                            i = i * 2;
                        }
                        image_rgb.Extent(new MagickGeometry(-(i / 2 - s.w / 2), -(i / 2 - s.h / 2), i, i), MagickColor.FromRgba(255, 255, 255, 0));
                        image_rgb.Write(folderPath + "/" + s.n);
                    }
                }
                //return;
            }
        }
        private MagickImage BuildImageWithPadding(MagickImage source)
        {
            int tilesWide = source.Width / Settings.TileX;
            int tilesHigh = source.Height / Settings.TileY;

            int newImageWidth  = source.Width + Settings.PaddingX * tilesWide * 2;
            int newImageHeight = source.Height + Settings.PaddingY * tilesHigh * 2;

            MagickImage result = new MagickImage(MagickColors.Transparent, newImageWidth, newImageHeight);

            IMagickImage <ushort>[]? tiles = source.CropToTiles(Settings.TileX, Settings.TileY).ToArray();

            for (int y = 0; y < tilesHigh; y++)
            {
                Progress.Report((int)(100 * ((float)(y + 1) / tilesHigh)));
                for (int x = 0; x < tilesWide; x++)
                {
                    using var subImage   = tiles[x + y * tilesWide];
                    subImage.BorderColor = MagickColors.Transparent;
                    subImage.Border(Settings.PaddingX, Settings.PaddingY);
                    using var subImagePixels = subImage.GetPixels();

                    ExtendEdge(subImagePixels, subImage.Width, subImage.Height);
                    result.Composite(subImage, x * subImage.Width, y * subImage.Height, CompositeOperator.SrcOver);
                }
            }

            return(result);
        }
Ejemplo n.º 19
0
        // Standard
        public CWatchImage(string name, int index, IMagickImage magickImage, double metricUpperBound)
        {
            Name             = name;
            Index            = index;
            MagickImage      = magickImage;
            HasAlpha         = MagickImage != null && MagickImage.HasAlpha;
            TransparencyRate = MagickImage != null?MagickImage.GetTransparencyRate() : 0;

            AlphaChannel     = null;
            MetricUpperBound = metricUpperBound;

            _PauseTicks = DateTime.MinValue.Ticks;

            if (HasAlpha)
            {
                // Does Separate() clone the channels? If so, does it dispose of them during this?
                var tmpMi = MagickImage.Separate().Last().Clone();
                tmpMi.Negate();
                AlphaChannel = new MagickImage(_AlphaReplacement, MagickImage.Width, MagickImage.Height);
                AlphaChannel.Composite(tmpMi, CompositeOperator.CopyAlpha);
                AlphaChannel.RePage();
                tmpMi.Dispose();

                MagickImage.ColorAlpha(_AlphaReplacement);
                MagickImage.RePage();
            }
        }
Ejemplo n.º 20
0
        public async Task <IActionResult> Isim(string adSoyad = "")
        {
            var layoutImage = Path.Combine(Directory.GetCurrentDirectory(), "arkaplan.jpeg");
            var newImage    = Path.Combine(Directory.GetCurrentDirectory(), "newImage.jpeg");
            var fontPath    = Path.Combine(Directory.GetCurrentDirectory(), "Helvetica.ttf");

            var layoutImg = new MagickImage(layoutImage);

            var readSettings = new MagickReadSettings()
            {
                Font            = fontPath,
                FontFamily      = "Helvetica",
                FillColor       = new MagickColor("#532547"),
                TextGravity     = Gravity.Center,
                BackgroundColor = MagickColors.Transparent,
                Height          = 30, // height of text box
                Width           = layoutImg.Width
            };

            using (var image = new MagickImage(layoutImg))
            {
                using (var caption = new MagickImage($"label:{"Sayın Abdulsamet İleri"}", readSettings))
                {
                    image.Composite(caption, 0, 35, CompositeOperator.Over);
                    image.Write(newImage);
                }
            }

            //return Redirect(newImage);
            var mm = new MemoryStream(System.IO.File.ReadAllBytes(newImage));

            return(Ok(mm));
        }
Ejemplo n.º 21
0
        public static void NeonSign()
        {
            using (var images = new MagickImage())
            {
                var backgroundImage = new MagickImage(new MagickColor(System.Drawing.Color.Black), 400, 175);

                var text = new MagickImage();

                text.Settings.BackgroundColor = new MagickColor();
                text.BorderColor            = new MagickColor(System.Drawing.Color.Black);
                text.Settings.FillColor     = System.Drawing.Color.DodgerBlue;
                text.Settings.FontPointsize = 72;
                text.Read("label:I M EXamples");

                var clone = text.Clone();
                clone.Blur(0, 25);
                clone.Level((Percentage)5, (Percentage)75);

                text.Composite(clone, CompositeOperator.Overlay);

                backgroundImage.Composite(text, CompositeOperator.Over);

                // backgroundImage.Composite(clone, CompositeOperator.Over);

                backgroundImage.Write("cloned.png");
            };
        }
Ejemplo n.º 22
0
        private void CreateMosaic(string outputPath)
        {
            var pixelSize = _archive.GetImageInfos().Size;

            var outputWidth  = _template.Width * pixelSize;
            var outputHeight = _template.Height * pixelSize;

            using var output = new MagickImage(new MagickColor("#FFFFFF"), outputWidth, outputHeight)
                  {
                      Format = MagickFormat.Png
                  };
            using var pixelCollection = _template.GetPixels();

            var pixelCountTotal = pixelCollection.Count();

            //Bar
            var bar = new ProgressBar(pixelCountTotal, "Assembling mosaic");

            foreach (var pixel in pixelCollection)
            {
                var outputX = pixel.X * pixelSize;
                var outputY = pixel.Y * pixelSize;

                using (var image = _archive.GetImage(_images[new Point(pixel.X, pixel.Y)]))
                {
                    output.Composite(image, outputX, outputY);
                }

                bar.Tick();
            }


            output.Write(outputPath);
        }
Ejemplo n.º 23
0
        public async Task StrongBadSays([Remainder] string input)
        {
            await Context.Channel.TriggerTypingAsync();

            using MemoryStream stream = new MemoryStream(256);
            using MagickImage image   = new MagickImage(Cache.GetStream("strongbadsays.png"));
            using MagickImage overlay = new MagickImage(Cache.GetStream("strongbadsays_overlay.png"));

            string text = string.Join(Environment.NewLine, input.SplitIntoChunks(47));
            int    max  = (text.Length <= 580 ? text.Length : 580);

            text = text.Substring(0, max);

            new Drawables()
            .FontPointSize(58)
            .Font(Path.Combine(Constants.FontsDirectory, "VT323-Regular.ttf"))
            .FillColor(new MagickColor("#CECCCC"))
            .TextAlignment(TextAlignment.Left)
            .TextAntialias(true)
            .TextEncoding(Encoding.UTF8)
            .Text(290, 190, text)
            .Draw(image);

            image.Composite(overlay, CompositeOperator.Atop);

            image.Write(stream, MagickFormat.Png);
            stream.Seek(0, SeekOrigin.Begin);

            await BetterSendFileAsync(stream, "strongbadSays.png", $"● {BetterUserFormat()}", parameters : input);
        }
Ejemplo n.º 24
0
        public EditableImage Apply(EditableImage image)
        {
            var bmp = image.Image;

            var borderWidth = (int)Math.Round(bmp.Width / 100 * BorderWidthPercentage);

            // For thicker borders try and keep to jpeg size blocks.
            if (borderWidth > 16)
            {
                borderWidth = (int)Math.Round(borderWidth / 8d) * 8;
            }

            int newWidth  = bmp.Width + borderWidth * 2;
            int newHeight = bmp.Height + borderWidth * 2;

            var newImage = new MagickImage(MagickColor.FromRgb(Colour.R, Colour.G, Colour.B), newWidth, newHeight);

            image.ApplyExistingSettingsToOtherImage(newImage);

            using (var clonedOriginal = image.Image.Clone())
            {
                newImage.Composite(clonedOriginal, Gravity.Center);

                image.Image = newImage;

                return(image);
            }
        }
Ejemplo n.º 25
0
        public static async Task BlendImages(string img1Path, string img2Path, string[] imgOutPaths)
        {
            try
            {
                MagickImage img1 = new MagickImage(img1Path);
                MagickImage img2 = new MagickImage(img2Path);

                int alphaFraction = (100f / (imgOutPaths.Length + 1)).RoundToInt();   // Alpha percentage per image
                int currentAlpha  = alphaFraction;

                foreach (string imgOutPath in imgOutPaths)
                {
                    string outPath = imgOutPath.Trim();

                    MagickImage img1Inst = new MagickImage(img1);
                    MagickImage img2Inst = new MagickImage(img2);

                    img2Inst.Alpha(AlphaOption.Opaque);
                    img2Inst.Evaluate(Channels.Alpha, EvaluateOperator.Set, new Percentage(currentAlpha));
                    currentAlpha += alphaFraction;

                    img1Inst.Composite(img2Inst, Gravity.Center, CompositeOperator.Over);
                    img1Inst.Format  = MagickFormat.Png24;
                    img1Inst.Quality = 10;
                    img1Inst.Write(outPath);
                    await Task.Delay(1);
                }
            }
            catch (Exception e)
            {
                Logger.Log("BlendImages Error: " + e.Message);
            }
        }
Ejemplo n.º 26
0
        private MagickImage RenderFrame(Image rawFrameImage, ConstAnimationFrame frameAnimationInfo, int smallestX, int largestX, int smallestY, int largestY, int normalizedWidth, int normalizedHeight)
        {
            MagickImage renderedFrame = new MagickImage(new MagickColor(0, 0, 0, 0), normalizedWidth, normalizedHeight);

            int normalizedFrameX = rawFrameImage.Attributes.LocationX - smallestX;
            int normalizedFrameY = rawFrameImage.Attributes.LocationY - smallestY;

            if (rawFrameImage.PixelData.Length > 0)
            {
                MagickReadSettings pixelDataSettings = new MagickReadSettings()
                {
                    ColorSpace   = ColorSpace.RGB,
                    Width        = rawFrameImage.Attributes.Width,
                    Height       = rawFrameImage.Attributes.Height,
                    PixelStorage = new PixelStorageSettings(StorageType.Char, "RGBA")
                };

                using (MagickImage rawFrameMagickImage = new MagickImage(rawFrameImage.PixelData, pixelDataSettings))
                {
                    rawFrameMagickImage.Format     = MagickFormat.Gif;
                    rawFrameMagickImage.MatteColor = new MagickColor(0, 0, 0, 0);
                    renderedFrame.Composite(rawFrameMagickImage, normalizedFrameX, normalizedFrameY, CompositeOperator.Over);
                }
            }

            renderedFrame.Format              = MagickFormat.Gif;
            renderedFrame.AnimationDelay      = frameAnimationInfo.DelayInMs / 10;
            renderedFrame.GifDisposeMethod    = GifDisposeMethod.Background;
            renderedFrame.AnimationIterations = 0;
            renderedFrame.MatteColor          = new MagickColor(0, 0, 0, 0);

            return(renderedFrame);
        }
Ejemplo n.º 27
0
        public static void AddTextToExistingImage()
        {
            var pathToBackgroundImage = SampleFiles.SampleBackground;
            var pathToNewImage        = Path.Combine(SampleFiles.OutputDirectory, "2FD-WithAddedText.jpg");
            var textToWrite           = "Insert This Text Into Image";

            // These settings will create a new caption
            // which automatically resizes the text to best
            // fit within the box.

            var readSettings = new MagickReadSettings
            {
                Font            = "Calibri",
                TextGravity     = Gravity.Center,
                BackgroundColor = MagickColors.Transparent,
                Height          = 250, // height of text box
                Width           = 680  // width of text box
            };

            using (var image = new MagickImage(pathToBackgroundImage))
            {
                using (var caption = new MagickImage($"caption:{textToWrite}", readSettings))
                {
                    // Add the caption layer on top of the background image
                    // at position 590,450
                    image.Composite(caption, 590, 450, CompositeOperator.Over);

                    image.Write(pathToNewImage);
                }
            }
        }
        private IMagickImage CreatePattern(int width, int height, IMagickImage texture)
        {
            var pattern = new MagickImage(MagickColors.None, width, height);

            pattern.Texture(texture);

            if (Spread == 0.0)
            {
                return(pattern);
            }

            if (Spread == 100.0)
            {
                pattern.Spread(Spread);
                return(pattern);
            }

            using (IMagickImage mix = pattern.Clone())
            {
                mix.Spread(Spread);

                pattern.Composite(mix, CompositeOperator.Blend, Mix.ToString(CultureInfo.InvariantCulture));
                return(pattern);
            }
        }
Ejemplo n.º 29
0
        public byte[] TakeImage()
        {
            using (var image = new MagickImage(MagickColor.FromRgba(0, 0, 0, 0), PageSize.Width, PageSize.Height))
            {
                image.Format = MagickFormat.Png32;
                for (var x = 0; x < HorizontalSnaps; x++)
                {
                    for (var y = 0; y < VerticalSnaps; y++)
                    {
                        Driver.SetOffset(x * ViewSize.Width, y * ViewSize.Height);
                        using (var part = new MagickImage(TakesScreenshot.GetScreenshot().AsByteArray))
                        {
                            UpdateOffsetX(out int oldOffsetX, out int diffX);
                            UpdateOffsetY(out int oldOffsetY, out int diffY);

                            var imageRectangle       = new Rectangle(OffsetX, OffsetY, ViewSize.Width, ViewSize.Height);
                            var horizontalRedundancy = Math.Max(0, imageRectangle.Right - PageSize.Width) * Math.Min(x, 1);
                            var verticalRedundancy   = Math.Max(0, imageRectangle.Bottom - PageSize.Height) * Math.Min(y, 1);

                            image.Composite(part, OffsetX - horizontalRedundancy, OffsetY - verticalRedundancy, CompositeOperator.Copy);
                        }
                    }
                }
                return(image.ToByteArray());
            }
        }
Ejemplo n.º 30
0
        /// <summary>
        /// Apply screen composition.
        /// </summary>
        /// <param name="image0">Base image.</param>
        /// <param name="image1">Image to apply screen composition.</param>
        /// <returns>Composed image.</returns>
        internal static MagickImage Screen(MagickImage image0, MagickImage image1)
        {
            var newImage = new MagickImage(image0);

            newImage.Composite(image1, CompositeOperator.Screen);
            return(newImage);
        }
Ejemplo n.º 31
0
        /// <summary>
        /// Adds two images.
        /// </summary>
        /// <param name="image0">Base image.</param>
        /// <param name="image1">Image to add.</param>
        /// <returns>Composed image.</returns>
        internal static MagickImage Add(MagickImage image0, MagickImage image1)
        {
            var newImage = new MagickImage(image0);

            newImage.Composite(image1, CompositeOperator.Plus);
            return(newImage);
        }
Ejemplo n.º 32
0
		public void Test_Composite()
		{
			using (MagickImage image = new MagickImage("logo:"))
			{
				using (MagickImage blur = new MagickImage(new MagickColor("#000"), image.Width, image.Height))
				{
					image.Warning += ShouldNotRaiseWarning;
					image.Composite(blur, Gravity.Center, CompositeOperator.Multiply);
				}
			}
		}
Ejemplo n.º 33
0
        private MagickImage RenderFrame(Image rawFrameImage, ConstAnimationFrame frameAnimationInfo, int smallestX, int largestX, int smallestY, int largestY, int normalizedWidth, int normalizedHeight)
        {
            MagickImage renderedFrame = new MagickImage(new MagickColor(0, 0, 0, 0), normalizedWidth, normalizedHeight);

            int normalizedFrameX = rawFrameImage.Attributes.LocationX - smallestX;
            int normalizedFrameY = rawFrameImage.Attributes.LocationY - smallestY;

            if (rawFrameImage.PixelData.Length > 0)
            {
                MagickReadSettings pixelDataSettings = new MagickReadSettings()
                {
                    ColorSpace = ColorSpace.RGB,
                    Width = rawFrameImage.Attributes.Width,
                    Height = rawFrameImage.Attributes.Height,
                    PixelStorage = new PixelStorageSettings(StorageType.Char, "RGBA")
                };

                using (MagickImage rawFrameMagickImage = new MagickImage(rawFrameImage.PixelData, pixelDataSettings))
                {
                    rawFrameMagickImage.Format = MagickFormat.Gif;
                    rawFrameMagickImage.MatteColor = new MagickColor(0, 0, 0, 0);
                    renderedFrame.Composite(rawFrameMagickImage, normalizedFrameX, normalizedFrameY, CompositeOperator.Over);
                }
            }

            renderedFrame.Format = MagickFormat.Gif;
            renderedFrame.AnimationDelay = frameAnimationInfo.DelayInMs / 10;
            renderedFrame.GifDisposeMethod = GifDisposeMethod.Background;
            renderedFrame.AnimationIterations = 0;
            renderedFrame.MatteColor = new MagickColor(0, 0, 0, 0);

            return renderedFrame;
        }