Esempio n. 1
0
        public void Test_RemoveAlpha()
        {
            string tempFile = GetTemporaryFileName(".png");

            try
            {
                using (MagickImage image = new MagickImage(Files.MagickNETIconPNG))
                {
                    Assert.IsTrue(image.HasAlpha);
                    image.ColorAlpha(new MagickColor("yellow"));
                    image.HasAlpha = true;
                    image.Write(tempFile);

                    image.Read(tempFile);

                    Assert.IsTrue(image.HasAlpha);

                    PngOptimizer optimizer = new PngOptimizer();
                    optimizer.LosslessCompress(tempFile);

                    image.Read(tempFile);
                    Assert.IsFalse(image.HasAlpha);
                }
            }
            finally
            {
                FileHelper.Delete(tempFile);
            }
        }
Esempio n. 2
0
        public void Test_RemoveAlpha()
        {
            string tempFile = Path.GetTempPath() + Guid.NewGuid().ToString() + ".png";

            try
            {
                using (MagickImage image = new MagickImage(Files.MagickNETIconPNG))
                {
                    Assert.IsTrue(image.HasAlpha);
                    image.ColorAlpha(new MagickColor("yellow"));
                    image.HasAlpha = true;
                    image.Write(tempFile);

                    image.Read(tempFile);

                    // TODO: Figure out why this does not fail in a single run but does when all tests are run.
                    //Assert.IsTrue(image.HasAlpha);

                    PngOptimizer optimizer = new PngOptimizer();
                    optimizer.LosslessCompress(tempFile);

                    image.Read(tempFile);
                    Assert.IsFalse(image.HasAlpha);
                }
            }
            finally
            {
                if (File.Exists(tempFile))
                {
                    File.Delete(tempFile);
                }
            }
        }
Esempio n. 3
0
        public static async Task ExtractAlpha(string inputDir, string outputDir, bool print = true, bool setProgress = true, bool removeInputAlpha = true)
        {
            try
            {
                var files = IOUtils.GetFilesSorted(inputDir);
                if (print)
                {
                    Logger.Log($"Extracting alpha channel from images...");
                }
                Directory.CreateDirectory(outputDir);
                Stopwatch sw = new Stopwatch();
                sw.Restart();
                int counter = 0;
                foreach (string file in files)
                {
                    MagickImage alphaImg = new MagickImage(file);

                    if (removeInputAlpha)
                    {
                        MagickImage rgbImg = alphaImg;
                        rgbImg.Format  = MagickFormat.Png24;
                        rgbImg.Quality = 10;
                        MagickImage bg = new MagickImage(MagickColors.Black, rgbImg.Width, rgbImg.Height);
                        bg.Composite(rgbImg, CompositeOperator.Over);
                        rgbImg = bg;
                        rgbImg.Write(file);
                    }

                    alphaImg.Format  = MagickFormat.Png24;
                    alphaImg.Quality = 10;

                    alphaImg.FloodFill(MagickColors.None, 0, 0);                   // Fill the image with a transparent background
                    alphaImg.InverseOpaque(MagickColors.None, MagickColors.White); // Change all the pixels that are not transparent to white.
                    alphaImg.ColorAlpha(MagickColors.Black);                       // Change the transparent pixels to black.

                    string outPath = Path.Combine(outputDir, Path.GetFileName(file));
                    alphaImg.Write(outPath);
                    counter++;
                    if (sw.ElapsedMilliseconds > 250)
                    {
                        if (setProgress)
                        {
                            Program.mainForm.SetProgress((int)Math.Round(((float)counter / files.Length) * 100f));
                        }
                        await Task.Delay(1);

                        sw.Restart();
                    }
                }
            }
            catch (Exception e)
            {
                Logger.Log("ExtractAlpha Error: " + e.Message);
            }
        }
        public override void Convert()
        {
            MagickImage image = Converter.MyPreviewImage;

            using (MagickImage color = new MagickImage(image.Clone()))
            {
                int length = Math.Max(color.Height, color.Width) + 2;
                length -= (length % 4);

                color.Format = MagickFormat.Png32;
                color.Extent(length, length, Gravity.Center, new MagickColor(0, 0, 0, 0));

                color.ColorAlpha(MagickColors.None);

                color.Format = MagickFormat.Dds;
                color.Settings.SetDefine(MagickFormat.Dds, "compression", "dxt5"); //dxt1, dxt5, none
                color.Settings.SetDefine(MagickFormat.Dds, "fast-mipmaps", "true");
                color.Settings.SetDefine(MagickFormat.Dds, "mipmaps", "10");
                color.Settings.SetDefine(MagickFormat.Dds, "cluster-fit", "true");
                color.Write(MyImagePath + "_c.dds");
            }

            if (GenerateMask)
            {
                using (MagickImage alpha = new MagickImage(image.Clone()))
                {
                    int length = Math.Max(alpha.Height, alpha.Width) + 2;
                    length -= (length % 4);

                    alpha.Format = MagickFormat.Png;
                    alpha.Extent(length, length, Gravity.Center, new MagickColor(0, 0, 0, 0));

                    alpha.Grayscale();
                    foreach (Pixel p in alpha.GetPixels())
                    {
                        MagickColor c = (MagickColor)p.ToColor();
                        p.SetChannel(0, c.A);
                        p.SetChannel(1, 0);
                    }

                    alpha.Format = MagickFormat.Dds;
                    alpha.Settings.SetDefine(MagickFormat.Dds, "compression", "dxt5"); //dxt1, dxt5, none
                    alpha.Settings.SetDefine(MagickFormat.Dds, "fast-mipmaps", "true");
                    alpha.Settings.SetDefine(MagickFormat.Dds, "mipmaps", "10");
                    alpha.Settings.SetDefine(MagickFormat.Dds, "cluster-fit", "true");
                    alpha.Write(MyImagePath + "_a.dds");
                }
            }
        }
Esempio n. 5
0
        public MagicCanvas(int width, int height, bool noAlpha = false)
        {
            var backColor = noAlpha
                                ? MagickColors.Black
                                : MagickColors.Transparent
            ;

            bitmap = new MagickImage(backColor, width, height);
            if (!noAlpha)
            {
                bitmap.ColorType = ColorType.TrueColorAlpha;
                bitmap.Alpha(AlphaOption.Transparent);
                bitmap.ColorAlpha(MagickColors.Transparent);
            }
        }
Esempio n. 6
0
        private void ApplyImage(int resizeWidth, int resizeHeight, Channels channel, string path, int x, int y)
        {
            int imgPadding = padding / 2;

            MagickImage imageToApply = new MagickImage(path);

            imageToApply.Transparent(new MagickColor("#000000"));
            imageToApply.FilterType = FilterType.Quadratic;
            imageToApply.Quality    = 100;
            imageToApply.Format     = MagickFormat.Png;
            imageToApply.ColorAlpha(new MagickColor("#000000"));
            MagickGeometry size = new MagickGeometry(resizeWidth - padding, resizeHeight - padding);

            size.IgnoreAspectRatio = true;
            imageToApply.Resize(size);
            imageToApply.ColorSpace = ColorSpace.LinearGray;

            workingImage.CopyPixels(imageToApply, size, (x * resizeWidth) + imgPadding, (y * resizeHeight) + imgPadding, channel);
        }
Esempio n. 7
0
                public void ShouldDisableAlphaChannelWhenPossible()
                {
                    using (TemporaryFile tempFile = new TemporaryFile("no-alpha.png"))
                    {
                        using (var image = new MagickImage(Files.MagickNETIconPNG))
                        {
                            Assert.IsTrue(image.HasAlpha);
                            image.ColorAlpha(new MagickColor("yellow"));
                            image.HasAlpha = true;
                            image.Write(tempFile);

                            image.Read(tempFile);

                            Assert.IsTrue(image.HasAlpha);

                            Optimizer.LosslessCompress(tempFile);

                            image.Read(tempFile);
                            Assert.IsFalse(image.HasAlpha);
                        }
                    }
                }
Esempio n. 8
0
        public void Test_RemoveAlpha()
        {
            using (TemporaryFile tempFile = new TemporaryFile("no-alpha.png"))
            {
                using (IMagickImage image = new MagickImage(Files.MagickNETIconPNG))
                {
                    Assert.IsTrue(image.HasAlpha);
                    image.ColorAlpha(new MagickColor("yellow"));
                    image.HasAlpha = true;
                    image.Write(tempFile);

                    image.Read(tempFile);

                    Assert.IsTrue(image.HasAlpha);

                    PngOptimizer optimizer = new PngOptimizer();
                    optimizer.LosslessCompress(tempFile);

                    image.Read(tempFile);
                    Assert.IsFalse(image.HasAlpha);
                }
            }
        }
Esempio n. 9
0
        public MemoryStream Execute(Stream stream, int width, int height)
        {
            bool isCMYK = false;

            using (MagickImage image = new MagickImage(stream))
            {
                if (image.ColorSpace == ColorSpace.CMYK)
                {
                    isCMYK = true;
                }
            }

            if (isCMYK)
            {
                var cymkConverter = new CYMK2RGB();
                stream = cymkConverter.ConvertCYMKToRGB(stream);
            }

            stream.Seek(0, SeekOrigin.Begin);

            MemoryStream memStream = new MemoryStream();

            // convert to size
            using (MagickImage image = new MagickImage(stream))
            {
                if (image.Height > height || image.Width > width)
                {
                    image.Resize(width, height);
                }
                image.ColorAlpha(MagickColors.White);
                image.Write(memStream, MagickFormat.Jpg);
            }

            memStream.Seek(0, SeekOrigin.Begin);
            return(memStream);
        }
        public virtual byte[] ConvertToPcx([NotNull] Bitmap bitmap)
        {
            if (bitmap == null)
            {
                throw new ArgumentNullException(nameof(bitmap));
            }

            // TODO merge with Svg.Contrib.Render.FingerPrint.FingerPrintTransformer.ConvertToPcx, Svg.Contrib.Render.FingerPrint

            var width = bitmap.Width;
            var mod   = width % 8;

            if (mod > 0)
            {
                width += 8 - mod;
            }
            var height = bitmap.Height;

            MagickImage magickImage;

#if NETSTANDARD2_0
            using (var memoryStream = new MemoryStream())
            {
                bitmap.Save(memoryStream,
                            bitmap.RawFormat);

                magickImage = new MagickImage(memoryStream);
            }
#else
            magickImage = new MagickImage(bitmap);
#endif

            using (magickImage)
            {
                if (mod > 0)
                {
                    var magickGeometry = new MagickGeometry(width,
                                                            height)
                    {
                        IgnoreAspectRatio = true
                    };
                    magickImage.Resize(magickGeometry);
                }

                if (magickImage.HasAlpha)
                {
                    magickImage.ColorAlpha(MagickColors.White);
                }

                var quantizeSettings = new QuantizeSettings
                {
                    Colors       = 2,
                    DitherMethod = DitherMethod.No
                };
                magickImage.Quantize(quantizeSettings);

                magickImage.ColorType = ColorType.Bilevel;
                magickImage.Depth     = 1;
                magickImage.Format    = MagickFormat.Pcx;

                magickImage.Density = new Density(bitmap.HorizontalResolution,
                                                  bitmap.VerticalResolution);

                magickImage.Negate(); // TODO see https://github.com/dlemstra/Magick.NET/issues/569

                var array = magickImage.ToByteArray();

                return(array);
            }
        }
        async Task <bool> EncodeDrivingLicense(ITask obj)
        {
            var o           = (DrivingLicense)obj;
            var holderPhoto = o.Holder.PhotoData;

            if (!String.IsNullOrEmpty(holderPhoto))
            {
                var photoData = Convert.FromBase64String(holderPhoto);
                using (var image = new MagickImage(photoData))
                {
                    image.Quality = 80;
                    image.Resize(275, 0);
                    o.Holder.PhotoData = image.ToBase64(MagickFormat.Jpeg);
                }
            }

            var holderSign = o.Holder.SignatureData;

            if (!String.IsNullOrEmpty(holderSign))
            {
                var signData = Convert.FromBase64String(holderSign);
                using (var image = new MagickImage(signData))
                {
                    image.Quality = 90;
                    image.Resize(165, 0);
                    image.BackgroundColor = MagickColors.White;
                    image.ColorAlpha(MagickColors.White);
                    o.Holder.SignatureData = image.ToBase64(MagickFormat.Jpeg);
                }
            }

            var jss = new JsonSerializerSettings
            {
                ContractResolver     = new DlPostContractResolver("card"),
                DateTimeZoneHandling = DateTimeZoneHandling.Local,
                DateFormatString     = "yyyyMMdd"
            };
            var json = JsonConvert.SerializeObject(o, Formatting.Indented, jss);

            int    rsCode;
            string cardSn;

            try
            {
                rsCode = await CardApi.WriteDriverInfo(json);

                cardSn = await CardApi.ReadUUidAsync();
            }
            catch
            {
                CurrentProdLine.SetPrinterPosition("RejectPosition");
                rtbLog.AppendText(String.Format(Texts.CardEncodingError, DateTime.Now.ToString("G")));
                rtbLog.AppendText(Environment.NewLine);
                return(false);
            }

            if (rsCode != 0)
            {
                CurrentProdLine.SetPrinterPosition("RejectPosition");
                rtbLog.AppendText(String.Format(Texts.CardEncodingError, DateTime.Now.ToString("G")));
                rtbLog.AppendText(Environment.NewLine);
                return(false);
            }

            o.CardSn               = cardSn;
            o.Holder.PhotoData     = holderPhoto;
            o.Holder.SignatureData = holderSign;
            return(true);
        }