Example #1
0
        public MagickImage GetText()
        {
            var image = new MagickImage(new MagickColor(255, 255, 255, 0), 4000, 2000);

            var drawables = new Drawables()
                            //.Rotation(30)
                            .Text(0, 0, Text)
                            .TextAntialias(true)
                            .Font("CarbonRegular W00")
                            .FontPointSize(387)
                            //.FontPointSize(360)
                            //.FontPointSize(-1)
                            .TextInterlineSpacing(-50)
                            .TextKerning(20)
                            //.TextKerning(9)
                            .FillColor(TextColor)
                            .Gravity(Gravity.West);

            //return drawables;
            image.Draw(drawables);

            image.Scale(new Percentage(GetScalingFactor() * 100));
            image.Trim();
            image.Extent(Math.Max(image.Width, image.Height), Math.Max(image.Width, image.Height), Gravity.West);
            image.BorderColor = new MagickColor("transparent");
            image.Border(20);
            image.BorderColor = new MagickColor("#ffffff01");
            image.Border(1);
            //image.Write("./text-face.png");

            return(image);
        }
Example #2
0
        public byte[] Squarify(byte[] image, Color backgroundColor, double borderSizeFactor, MagickFormat format)
        {
            using (var magickImage = new MagickImage(image))
            {
                int width  = 0;
                int height = 0;

                if (magickImage.Width > magickImage.Height)
                {
                    width  = GetLongSide(magickImage.Width, borderSizeFactor);
                    height = GetShortSide(magickImage.Height, magickImage.Width, width);
                }
                else
                {
                    height = GetLongSide(magickImage.Height, borderSizeFactor);
                    width  = GetShortSide(magickImage.Width, magickImage.Height, height);
                }

                magickImage.Border(width, height);
                magickImage.BorderColor = MagickColor.FromRgb(backgroundColor.R, backgroundColor.G, backgroundColor.B);
                magickImage.Format      = format;

                return(magickImage.ToByteArray());
            }
        }
        public static byte[] ToPng <T>([NotNull] this T[,] @this, Func <T, Color> selector, int scaleFactor = 4, int border = 10)
        {
            var(cx, cy) = @this.GetDimensions();

            using var image = new MagickImage(MagickColors.Black, cx, cy);
            image.Density   = new Density(100, DensityUnit.PixelsPerInch);

            using (var outPixels = image.GetPixels())
            {
                var bytes = new byte[3];
                foreach (var(x, y, c) in @this.SelectCells().SelectXy())
                {
                    var color = selector(c);
                    bytes[0] = color.R;
                    bytes[1] = color.G;
                    bytes[2] = color.B;
                    outPixels[x, y].Set(bytes);
                }
            }

            image.Scale(new Percentage(scaleFactor * 100));

            image.BorderColor = image.BackgroundColor;
            image.Border(border);

            var stream = new MemoryStream();

            image.Write(stream, MagickFormat.Png);

            return(stream.GetBuffer());
        }
Example #4
0
        public static void GradientBackground()
        {
            using (MagickImage image = new MagickImage("gradient:blue-darkblue", 400, 175))
            {
                image.Swirl(45);
                image.Border(2);

                using (var text = new MagickImage("gradient:blue-red"))
                {
                    text.Settings.Font = "Arial";
                    //text.Morphology(MorphologyMethod.EdgeIn, Kernel.Diamond);

                    text.Settings.FontPointsize = 70;

                    //text.Tile(new MagickImage("gradient:blue-red"),CompositeOperator.Overlay);

                    text.Annotate("Gradient Fun", new MagickGeometry("+10+65"), Gravity.Center);

                    text.Write("text.png");
                    image.Composite(text, CompositeOperator.Over);
                }

                image.Write("preview.png");
            }
        }
Example #5
0
        private void Distort(MagickImage output, PointD[] corners, MagickGeometry inputDimensions, MagickGeometry trimmedDimensions, MagickColor backgroundColor)
        {
            MagickGeometry outputDimensions = GetDimensions(output, corners, inputDimensions, trimmedDimensions);

            double[] arguments = new double[16]
            {
                corners[0].X, corners[0].Y, 0, 0,
                corners[1].X, corners[1].Y, 0, outputDimensions.Height,
                corners[2].X, corners[2].Y, outputDimensions.Width, outputDimensions.Height,
                corners[3].X, corners[3].Y, outputDimensions.Width, 0
            };

            output.VirtualPixelMethod = VirtualPixelMethod.Background;
            output.BackgroundColor    = backgroundColor;
            if (!DisableViewportCrop)
            {
                output.SetArtifact("distort:viewport", GetViewport(arguments, corners).ToString());
            }
            output.Distort(DistortMethod.Perspective, true, arguments);
            output.BorderColor = backgroundColor;
            output.Border(2);
            output.ColorFuzz = ColorFuzz;
            output.Trim();
            output.RePage();
        }
Example #6
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");
            }
        }
Example #7
0
        private MagickGeometry TrimImage(MagickImage image, MagickColor backgroundColor, int borderSize)
        {
            image.BorderColor = backgroundColor;
            image.Border(borderSize);
            image.ColorFuzz = ColorFuzz;
            image.Trim();
            image.RePage();

            return(new MagickGeometry(image.Width, image.Height));
        }
Example #8
0
            public void ShouldOnlyAddVerticalBorderWhenOnlyWidthIsSpecified()
            {
                using (var image = new MagickImage("xc:red", 1, 1))
                {
                    image.Border(3, 0);

                    Assert.Equal(7, image.Width);
                    Assert.Equal(1, image.Height);
                }
            }
Example #9
0
            public void ShouldOnlyAddHorizontalBorderWhenOnlyHeightIsSpecified()
            {
                using (var image = new MagickImage("xc:red", 1, 1))
                {
                    image.Border(0, 3);

                    Assert.Equal(1, image.Width);
                    Assert.Equal(7, image.Height);
                }
            }
Example #10
0
        private void PadImage(MagickImage image)
        {
            if (Padding == 0)
            {
                return;
            }

            image.Compose     = CompositeOperator.Over;
            image.BorderColor = BackgroundColor;
            image.Border(Padding);
        }
Example #11
0
            public void ShouldAddBorderOnAllSides()
            {
                using (var image = new MagickImage("xc:red", 1, 1))
                {
                    image.BorderColor = MagickColors.Green;
                    image.Border(3);

                    Assert.Equal(7, image.Width);
                    Assert.Equal(7, image.Height);
                    ColorAssert.Equal(MagickColors.Green, image, 1, 1);
                }
            }
Example #12
0
        public IEnumerable <byte> PreProcess(IEnumerable <byte> bitmap)
        {
            using (var processed = new MagickImage(bitmap.ToArray()))
            {
                processed.ColorSpace = ColorSpace.Gray;
                processed.ColorType  = ColorType.Grayscale;

                processed.Normalize();

                // Denoise
                using (var denoise = processed.Clone())
                {
                    denoise.ColorSpace = ColorSpace.Gray;
                    denoise.Negate();
                    denoise.AdaptiveThreshold(10, 10, new Percentage(5));
                    denoise.ContrastStretch(new Percentage(0));
                    processed.Composite(denoise, CompositeOperator.CopyAlpha);
                }
                processed.Opaque(MagickColors.Transparent, MagickColors.White);
                processed.Alpha(AlphaOption.Off);

                // Deskew
                processed.BackgroundColor = MagickColors.White;
                processed.Deskew(new Percentage(40));

                // Sharpen
                processed.Sharpen(0, 1);

                // Saturate
                processed.Modulate(new Percentage(100), new Percentage(200), new Percentage(100));

                // Trim
                processed.Trim();
                processed.RePage();

                processed.Compose     = CompositeOperator.Over;
                processed.BorderColor = MagickColors.White;
                processed.Border(15);

                return(processed.ToByteArray());
            }
        }
Example #13
0
        public static string OcrSmallText(Int2 size, Func <Int2, bool> isSet)
        {
            var imagePath = Path.GetTempFileName().ToNPath();

            try
            {
                // to detect small text, tesseract needs black on white with a border and scaled up 400%
                using (var image = new MagickImage(MagickColors.White, size.X, size.Y))
                {
                    image.Density = new Density(100, DensityUnit.PixelsPerInch);

                    using (var outPixels = image.GetPixels())
                    {
                        for (var y = 0; y < image.Height; ++y)
                        {
                            for (var x = 0; x < image.Width; ++x)
                            {
                                if (isSet(new Int2(x, y)))
                                {
                                    outPixels[x, y].Set(k_On);
                                }
                            }
                        }
                    }

                    image.Scale(new Percentage(400));

                    image.BorderColor = image.BackgroundColor;
                    image.Border(10);

                    image.Write(imagePath, MagickFormat.Png);
                }

                var(stdout, stderr) = (new List <string>(), new List <string>());
                ProcessUtility.ExecuteCommandLine("tesseract", Arr(imagePath.ToString(), "stdout"), null, stdout, stderr);
                return(stdout[0]);
            }
            finally
            {
                imagePath.DeleteIfExists();
            }
        }
Example #14
0
        public void PrepareForPlate(MagickImage image, Plate plate, Gravity gravity = Gravity.Center, bool extent = true)
        {
            image.BackgroundColor = new MagickColor(255, 255, 255, 0);
            switch (plate)
            {
            case Plate.Left:
                if (extent)
                {
                    image.Trim();
                    image.Extent(Math.Max(image.Width, image.Height), Math.Max(image.Width, image.Height), gravity);
                    image.BorderColor = new MagickColor("transparent");
                    image.Border(20);
                    image.BorderColor = new MagickColor("#ffffff01");
                    image.Border(1);
                }
                image.Shear(-30, 0);
                image.Rotate(30);
                break;

            case Plate.Right:
                image.Trim();
                image.Extent(Math.Max(image.Width, image.Height), Math.Max(image.Width, image.Height), gravity);
                image.BorderColor = new MagickColor("transparent");
                image.Border(20);
                image.BorderColor = new MagickColor("#ffffff01");
                image.Border(1);
                image.Shear(30, 0);
                image.Rotate(-30);
                break;

            case Plate.Top:
                //image.Scale(new Percentage(GetScalingFactor() * 100));
                image.Trim();
                image.Extent(Math.Max(image.Width, image.Height), Math.Max(image.Width, image.Height), gravity);
                image.BorderColor = new MagickColor("transparent");
                image.Border(10);
                image.BorderColor = new MagickColor("#ffffff01");
                image.Border(1);
                image.Shear(30, 0);
                image.Rotate(30);
                break;
            }
            image.Trim();
        }
Example #15
0
        public byte[] GenerateNewImg(EntityNewsModel entityNewsModel)
        {
            var typeSettingHelper = new TypeSettingHelper();

            //内容
            var wordsArray = typeSettingHelper.GetTypeSettingArray(entityNewsModel.Content, 36);
            var titleArray = typeSettingHelper.GetTypeSettingArray(entityNewsModel.Title, 28);

            //主图左边距
            var mainImgMarginLeft = 93;

            //标题距离顶部间距
            var titleTopMrgin = 63;

            //标题字体高度
            var titleFontHeight = 50;

            //标题字体上下间距
            var titleFontPadding = 40;

            //标题距离横线间距
            var titleSpaceLine = 88;

            //内容填充边距
            var contentPadding = 62;

            //主图上边距
            var mainImgMarginTop = 140;

            //主图宽度
            var mainImgWidth = 894;

            //内容距离横线上边距
            var contentTopMrgin = 90;

            //内容字体上下间距
            var contentFontPadding = 49;

            //内容字体高度
            var contentFontHeight = 40;

            //内容距离下边距
            var contentBottomMargin = 102;

            //底部高度,包含二维码
            var bottomHeight = 321;

            //二维码上边距
            var wechatCodeTopMargin = 71;

            //二维码左边距
            var wechatCodeLeftMargin = 337;

            //微信二维码图片高度
            var wechatCodeImgHeight = 168;

            //标题图片总高度
            var titleHeight = titleTopMrgin + titleSpaceLine + titleFontHeight * titleArray.Length + (titleArray.Length - 1) * titleFontPadding;

            //新闻内容模块总高度
            var contentHeight = contentTopMrgin + contentBottomMargin + wordsArray.Length * contentFontHeight + (wordsArray.Length - 1) * contentFontPadding;

            var microsoftYaheiUi = "SimHei";
            var picHeight        = titleHeight + contentHeight;
            var lineColor        = new MagickColor("gray");

            using (var image = new MagickImage(new MagickColor("#F9F8F6"), 1080, picHeight + bottomHeight + mainImgMarginTop))
            {
                using (var mainImgImage = new MagickImage(new MagickColor("#FFFFFF"), mainImgWidth, picHeight))
                {
                    //title
                    for (var i = 0; i < titleArray.Length; i++)
                    {
                        new Drawables()
                        .TextEncoding(Encoding.UTF8)
                        .TextAntialias(true)
                        .FontPointSize(55)
                        .FillColor(new MagickColor(126, 99, 43))
                        .Gravity(Gravity.Northwest)
                        .Font(microsoftYaheiUi)
                        .Text(contentPadding, titleTopMrgin + ((titleFontHeight + titleFontPadding) * i), titleArray[i])
                        .Draw(mainImgImage);
                    }

                    for (var i = 2; i < 81; i++)
                    {
                        var beginWidth = 30 + 10 * i;
                        var endWidth   = 35 + 10 * i;

                        //头部间隔线
                        new Drawables().StrokeWidth(0.5).StrokeColor(lineColor).Line(beginWidth, titleHeight, endWidth, titleHeight).Draw(mainImgImage);
                    }

                    for (var i = 0; i < wordsArray.Length; i++)
                    {
                        new Drawables()
                        .TextEncoding(Encoding.UTF8)
                        .TextAntialias(true)
                        .FontPointSize(43)
                        .FillColor(new MagickColor(102, 102, 102))
                        .Gravity(Gravity.Northwest)
                        .Font(microsoftYaheiUi)
                        .Text(contentPadding, titleHeight + contentTopMrgin + (contentFontPadding + contentFontHeight) * i, wordsArray[i])
                        .Draw(mainImgImage);
                    }
                    //尾部
                    //new Drawables().StrokeWidth(0.5).StrokeColor(lineColor).Line(20, picHeight - 180, 880, picHeight - 180).Draw(mainImgImage);
                    mainImgImage.Border(1);
                    mainImgImage.BorderColor = new MagickColor("#4D4D4D");
                    image.Composite(mainImgImage, mainImgMarginLeft, mainImgMarginTop, CompositeOperator.Over);
                }

                //小程序二维码
                var client = new WebClient();
                using (var watermark = new MagickImage(client.DownloadData("http://img.blockcomet.com/wechatCode.png")))
                {
                    var size = new MagickGeometry(wechatCodeImgHeight, wechatCodeImgHeight)
                    {
                        IgnoreAspectRatio = true
                    };
                    watermark.Resize(size);
                    watermark.Evaluate(Channels.Black, EvaluateOperator.Divide, 4);

                    image.Composite(watermark, wechatCodeLeftMargin, picHeight + wechatCodeTopMargin + mainImgMarginTop, CompositeOperator.Over);
                }

                new Drawables()
                .TextEncoding(Encoding.UTF8)
                .TextAntialias(true)
                .FontPointSize(50)
                .FillColor(new MagickColor(102, 102, 102))
                .Gravity(Gravity.Northwest)
                .Font(microsoftYaheiUi)
                .Text(wechatCodeImgHeight + wechatCodeLeftMargin + 30, picHeight + mainImgMarginTop + 123, "彗星播报")
                .Draw(image);

                return(image.ToByteArray(MagickFormat.Jpg));
            }
            //return imgUrl;
        }
Example #16
0
        /// <summary>
        /// Method to perform file modification using Magick.Net
        /// </summary>
        /// <returns>Path to the new file ( modified )</returns>
        public async Task <DefaultServiceResponse> ModifyFile(ModifyModel model)
        {
            // Get last uploaded photo by the customer
            var lastUploadedImageName = DataContext.CustomerImageFiles.ToList().Where(imageFile => imageFile.CustomerId == model.UserId).OrderByDescending(orderBy => orderBy.UploadTime).Select(response => response.FullName);

            var intesivity = model.Intesivity;

            var editedFileName = "";

            using (var image = new MagickImage(lastUploadedImageName.First()))
            {
                switch (model.SelectedOperation)
                {
                case "CycleColorMap":
                    image.CycleColormap(intesivity);
                    break;

                case "FloodFill":
                    image.FloodFill(10, 10, 10);
                    break;

                case "Flop":
                    image.Flop();
                    break;

                case "GammaCorrect":
                    image.GammaCorrect(intesivity);     // gramma
                    break;

                case "GausiianBlur":
                    image.GaussianBlur(intesivity, intesivity);     // double radius + double sigma
                    break;

                case "MedianFilter":
                    image.MedianFilter(intesivity);     // radius
                    break;

                case "MotionBlur":
                    image.MotionBlur(10, 10, 10);
                    break;

                case "Negate":
                    image.Negate();     // simple negate
                    break;

                default:
                    break;
                }
                if (model.UseFrame)
                {
                    image.Border(7, 7);
                }

                editedFileName = lastUploadedImageName.First().Replace(Path.GetFileNameWithoutExtension(lastUploadedImageName.First()), Path.GetFileNameWithoutExtension(lastUploadedImageName.First()) + "_modified").Replace(Path.GetExtension(lastUploadedImageName.First()), "." + model.OutputFileType.ToLower());
                using (File.Create(editedFileName))
                    image.Write(editedFileName);
            }

            // Save file to the DB

            var originalImageId = DataContext.CustomerImageFiles.Where(imageData => imageData.CustomerId == model.UserId && imageData.FullName.Contains(Path.GetFileNameWithoutExtension(lastUploadedImageName.First()))).Select(result => result.Id).First();

            await DataContext.CustomerEditedImageFiles.AddAsync(new ResultImageFIleModel
            {
                Id              = new Guid(),
                CustomerId      = model.UserId,
                FullName        = editedFileName,
                OriginalImageId = originalImageId.ToString(),
                UploadTime      = DateTime.Now
            });

            await DataContext.SaveChangesAsync();

            return(new DefaultServiceResponse {
                ResponseData = "../" + Path.Combine("CustomersImages", Path.GetFileName(editedFileName))
            });
        }
Example #17
0
 private static void PadImage(MagickImage image, int borderSize)
 {
     image.Border(borderSize);
 }