예제 #1
0
                public void ShouldWriteCustomPolicyToDisk()
                {
                    string policy = @"<test/>";

                    string path = null;

                    try
                    {
                        var configFiles = ConfigurationFiles.Default;
                        configFiles.Policy.Data = policy;

                        path = MagickNET.Initialize(configFiles);

                        Assert.AreEqual(policy, File.ReadAllText(Path.Combine(path, "policy.xml")));
                    }
                    finally
                    {
                        Cleanup.DeleteDirectory(path);
                    }
                }
예제 #2
0
        private void Log_LogDelegateIsRemove_LogDelegateIsNoLongerCalled()
        {
            using (IMagickImage image = new MagickImage(Files.SnakewarePNG))
            {
                int count = 0;
                EventHandler <LogEventArgs> logDelegate = (sender, arguments) =>
                {
                    count++;
                };

                MagickNET.Log += logDelegate;

                MagickNET.SetLogEvents(LogEvents.Detailed);

                MagickNET.Log -= logDelegate;

                image.Flip();
                Assert.AreEqual(0, count);
            }
        }
        //===========================================================================================
        private void WriteExecute(IndentedTextWriter writer, string name)
        {
            MemberInfo member = (from property in Properties
                                 where MagickNET.GetXsdName(property).Equals(name, StringComparison.OrdinalIgnoreCase)
                                 select property).FirstOrDefault();

            if (member == null)
            {
                member = (from overloads in Methods
                          let method = overloads[overloads.Length - 1]
                                       where MagickNET.GetXsdName(method).Equals(name, StringComparison.OrdinalIgnoreCase)
                                       select method).FirstOrDefault();
            }


            if (ReturnType != "void")
            {
                writer.Write("return ");
            }
            writer.Write("Execute");
            if (member == null)
            {
                writer.Write(char.ToUpper(name[0]));
                writer.Write(name.Substring(1));
            }
            else
            {
                writer.Write(GraphicsMagickNET.GetName(member));
            }
            writer.Write("(");
            if (member == null || !IsStatic(member))
            {
                writer.Write("element, ");
            }
            writer.Write(ExecuteArgument.Split(' ').Last());
            writer.WriteLine(");");
            if (ReturnType == "void")
            {
                writer.WriteLine("return;");
            }
        }
 //===========================================================================================
 public override void WriteCode(IndentedTextWriter writer)
 {
     writer.Write(TypeName);
     writer.Write(" MagickScript::Create");
     writer.Write(ClassName);
     writer.WriteLine("(XmlElement^ element)");
     WriteStartColon(writer);
     foreach (string name in MagickNET.GetColorProfileNames())
     {
         writer.Write("if (element->GetAttribute(\"name\") == \"");
         writer.Write(name);
         writer.WriteLine("\")");
         writer.Indent++;
         writer.Write("return ColorProfile::");
         writer.Write(name);
         writer.WriteLine(";");
         writer.Indent--;
     }
     writer.WriteLine("throw gcnew NotImplementedException(element->Name);");
     WriteEndColon(writer);
 }
        //===========================================================================================
        private void WriteExecute(IndentedTextWriter writer)
        {
            writer.Write(ReturnType);
            writer.Write(" MagickScript::Execute");
            writer.Write(ExecuteName);
            writer.Write("(XmlElement^ element, ");
            writer.Write(ExecuteArgument);
            writer.WriteLine(")");
            WriteStartColon(writer);

            IEnumerable <string> names = (from property in Properties
                                          select MagickNET.GetXsdName(property)).Concat(
                from method in Methods
                select MagickNET.GetXsdName(method[0])).Concat(
                CustomMethods);

            WriteSwitch(writer, names, 0);

            writer.WriteLine("throw gcnew NotImplementedException(element->Name);");
            WriteEndColon(writer);
        }
예제 #6
0
        public void Test_Unregister()
        {
            using (MagickImage image = new MagickImage(Files.SnakewarePNG))
            {
                using (MemoryStream memoryStream = new MemoryStream())
                {
                    image.Resize(256, 256);
                    image.Format = MagickFormat.Ico;
                    image.Write(memoryStream);
                    memoryStream.Position = 0;

                    MagickFormatInfo formatInfo = MagickNET.GetFormatInformation(MagickFormat.Ico);
                    Assert.IsNotNull(formatInfo);
                    Assert.IsTrue(formatInfo.Unregister());

                    ExceptionAssert.Throws <MagickMissingDelegateErrorException>(delegate()
                    {
                        new MagickImage(memoryStream);
                    });
                }
            }
        }
예제 #7
0
        public void ConvertToScanned(string filename)
        {
            MagickReadSettings settings = new MagickReadSettings
            {
                Density = new Density(300, 300)
            };

            MagickNET.SetGhostscriptDirectory(Path.GetDirectoryName(GhostScriptHelper.GetGhostscriptVersion().DllPath));

            List <string> scannedimgfiles = new List <string>();

            using (MagickImageCollection images = new MagickImageCollection())
            {
                images.Read(filename, settings);

                int page = 1;

                foreach (MagickImage image in images)
                {
                    image.ColorSpace = ColorSpace.Gray;
                    var clone = image.Clone();
                    clone.Blur(0, 1);
                    clone.Compose = CompositeOperator.DivideDst;
                    image.Composite(clone);
                    image.LinearStretch(new Percentage(5), new Percentage(0));
                    image.Rotate(0.2);

                    var tempimgpath = Path.GetTempPath() + Path.GetFileNameWithoutExtension(filename) + "_img_" + page + ".png";
                    image.Write(tempimgpath);
                    scannedimgfiles.Add(tempimgpath);

                    page++;
                }
            }

            new ITextHelper().ImageToPdf(scannedimgfiles, filename);

            scannedimgfiles.ForEach(f => File.Delete(f));
        }
예제 #8
0
        public void Initialize_XmlFileIsMissing_ThrowsException()
        {
            string path = Files.Root + @"..\..\Source\Magick.NET.Native\Resources\xml";

            foreach (string fileName in Directory.GetFiles(path, "*.xml"))
            {
                string tempFile = fileName + ".tmp";

                if (File.Exists(tempFile))
                {
                    File.Delete(tempFile);
                }

                File.Move(fileName, tempFile);

                ExceptionAssert.Throws <ArgumentException>(delegate()
                {
                    MagickNET.Initialize(path);
                }, "MagickNET._ImageMagickFiles does not contain: " + Path.GetFileName(fileName));

                File.Move(tempFile, fileName);
            }
        }
예제 #9
0
        public void Test_GetFormatInformation()
        {
            MagickFormatInfo formatInfo = MagickNET.GetFormatInformation(MagickFormat.Gradient);

            Assert.AreEqual(MagickFormat.Gradient, formatInfo.Format);
            Assert.AreEqual(true, formatInfo.CanReadMultithreaded);
            Assert.AreEqual(true, formatInfo.CanWriteMultithreaded);
            Assert.AreEqual("Gradual linear passing from one shade to another", formatInfo.Description);
            Assert.AreEqual(false, formatInfo.IsMultiFrame);
            Assert.AreEqual(true, formatInfo.IsReadable);
            Assert.AreEqual(false, formatInfo.IsWritable);
            Assert.AreEqual(null, formatInfo.MimeType);

            formatInfo = MagickNET.GetFormatInformation(MagickFormat.Jp2);
            Assert.AreEqual(MagickFormat.Jp2, formatInfo.Format);
            Assert.AreEqual(true, formatInfo.CanReadMultithreaded);
            Assert.AreEqual(true, formatInfo.CanWriteMultithreaded);
            Assert.AreEqual("JPEG-2000 File Format Syntax", formatInfo.Description);
            Assert.AreEqual(false, formatInfo.IsMultiFrame);
            Assert.AreEqual(true, formatInfo.IsReadable);
            Assert.AreEqual(true, formatInfo.IsWritable);
            Assert.AreEqual("image/jp2", formatInfo.MimeType);
        }
예제 #10
0
        public void Initialize_WithCustomPolicy_PolicyIsWrittenToDisk()
        {
            string policy = @"<test/>";

            string path = null;

            try
            {
                ConfigurationFiles configFiles = ConfigurationFiles.Default;
                configFiles.Policy.Data = policy;

                path = MagickNET.Initialize(configFiles);

                Assert.AreEqual(policy, File.ReadAllText(Path.Combine(path, "policy.xml")));
            }
            finally
            {
                if (path != null)
                {
                    Directory.Delete(path, true);
                }
            }
        }
예제 #11
0
            private void ShouldLogTraceEventsWhenLogEventsIsSetToAll()
            {
                int traceEvents = 0;
                EventHandler <LogEventArgs> logDelegate = (sender, arguments) =>
                {
                    if (arguments.EventType == LogEvents.Trace)
                    {
                        traceEvents++;
                    }
                };

                MagickNET.SetLogEvents(LogEvents.All);

                MagickNET.Log += logDelegate;

                using (var image = new MagickImage(Files.SnakewarePNG))
                {
                }

                MagickNET.Log -= logDelegate;

                Assert.AreNotEqual(0, traceEvents);
            }
예제 #12
0
            public void ShouldReturnFormatInfoForAllFormats()
            {
                List <string> missingFormats = new List <string>();

                foreach (MagickFormat format in Enum.GetValues(typeof(MagickFormat)))
                {
                    if (format == MagickFormat.Unknown)
                    {
                        continue;
                    }

                    MagickFormatInfo formatInfo = MagickNET.GetFormatInformation(format);
                    if (formatInfo == null)
                    {
                        missingFormats.Add(format.ToString());
                    }
                }

                if (missingFormats.Count > 0)
                {
                    Assert.Fail("Cannot find MagickFormatInfo for: " + string.Join(", ", missingFormats.ToArray()));
                }
            }
예제 #13
0
        public ImageSource GetPage(string ghostScriptPath, string pdfFile, int pageNumber)
        {
            MagickNET.SetGhostscriptDirectory(ghostScriptPath);

            using (MagickImageCollection collection = new MagickImageCollection())
            {
                MagickReadSettings settings = new MagickReadSettings();
                settings.FrameIndex = pageNumber;

                settings.FrameCount = 1;

                try
                {
                    collection.Read(pdfFile, settings);
                }
                catch (MagickException)
                {
                    return(null);
                }


                return(SetBitmapImageFromBitmap(collection.ToBitmap(System.Drawing.Imaging.ImageFormat.Jpeg)));
            }
        }
예제 #14
0
            private void ShouldLogTraceEventsWhenLogEventsIsSetToAll()
            {
                int traceEvents = 0;

                void LogDelegate(object sender, LogEventArgs arguments)
                {
                    if (arguments.EventType == LogEvents.Trace)
                    {
                        traceEvents++;
                    }
                }

                MagickNET.SetLogEvents(LogEvents.All);

                MagickNET.Log += LogDelegate;

                using (var image = new MagickImage(Files.SnakewarePNG))
                {
                }

                MagickNET.Log -= LogDelegate;

                Assert.NotEqual(0, traceEvents);
            }
예제 #15
0
        private static void SetMagickNetTempDir(string imTemptDir)
        {
            if (string.IsNullOrEmpty(imTemptDir))
            {
                return;
            }

            if (!Directory.Exists(imTemptDir))
            {
                throw new InvalidOperationException($"Can't call MagickNET.SetTempDirectory(...) " +
                                                    $"with ... = '{imTemptDir}'");
            }

            try
            {
                MagickNET.SetTempDirectory(imTemptDir);
            }
            catch (MagickException e)
            {
                Console.WriteLine($"Error when calling MagickNET.SetTempDirectory(...) " +
                                  $"with ... = '{imTemptDir}'", e);
                throw;
            }
        }
예제 #16
0
        private string GerarImagem(Stream stream)
        {
            MagickNET.SetGhostscriptDirectory(Directory.GetCurrentDirectory());
            MagickNET.SetTempDirectory(Path.GetTempPath());

            var settings = new MagickReadSettings
            {
                Density = new Density(300, 300)
            };

            using (var images = new MagickImageCollection())
            {
                images.Read(stream, settings);

                using (var imagem = images.AppendHorizontally())
                {
                    var caminhoArquivo = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".png");
                    imagem.Format = MagickFormat.Png;
                    imagem.Write(caminhoArquivo);

                    return(caminhoArquivo);
                }
            }
        }
예제 #17
0
        public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequestMessage req, TraceWriter log)
        {
            log.Info("C# HTTP trigger function processed a request.");
            if (req.Method != HttpMethod.Get)
            {
                //Send an Error if wrong HTTP method is used
                return(req.CreateErrorResponse(HttpStatusCode.BadRequest, "This function currently only supports GET requests"));
            }

            // parse query parameter
            string pdfUrl = req.GetQueryNameValuePairs()
                            .FirstOrDefault(q => string.Compare(q.Key, "pdfurl", true) == 0)
                            .Value;

            if (pdfUrl == null)
            {
                return(req.CreateErrorResponse(HttpStatusCode.BadRequest, "You need to provide a url via pdfurl option"));
            }

            log.Info("Got PDF Option. Downloading: " + pdfUrl);
            //Get PDF Document
            WebClient webClient = new WebClient();
            Stream    pdfStream = new MemoryStream(webClient.DownloadData(pdfUrl));

            //SetUp ImageMagick
            string ghostPath = $@"{AppFolder}\".Replace('\\', '/');
            var    debug     = Directory.GetFiles(ghostPath);

            log.Info("Setting up ImageMagick");

            foreach (var item in debug)
            {
                log.Info("Found file: " + item);
            }

            MagickNET.SetGhostscriptDirectory(ghostPath);
            MagickReadSettings settings = new MagickReadSettings();

            settings.Density = new Density(300, 300);

            //Convert PDF to JPG
            log.Info("Start converting");
            MemoryStream jpegStream = new MemoryStream();

            using (MagickImageCollection images = new MagickImageCollection())
            {
                images.Read(pdfStream, settings);
                foreach (MagickImage image in images)
                {
                    image.Format = MagickFormat.Jpeg;
                    image.Write(jpegStream);
                }
            }
            log.Info("Finished converting");

            //Create HTTP response
            log.Info("Creating response");
            var result = req.CreateResponse(HttpStatusCode.OK);

            result.Content = new ByteArrayContent(jpegStream.ToArray());
            result.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("image/jpeg");
            return(result);
        }
 public void ShouldNotThrowExceptionWhenPathIsCorrect()
 {
     MagickNET.SetTempDirectory(Path.GetTempPath());
 }
예제 #19
0
 protected IEnumerable <Type> GetTypes()
 {
     return(MagickNET.GetTypes());
 }
예제 #20
0
        public Form1()
        {
            InitializeComponent();

            MagickNET.SetTempDirectory(TempFolder);
        }
                public void ShouldThrowExceptionWhenFilenameIsEmpty()
                {
                    var exception = Assert.Throws <ArgumentException>(() => MagickNET.GetFormatInformation(string.Empty));

                    Assert.Equal("fileName", exception.ParamName);
                }
예제 #22
0
 public void SetTempDirectory_PathIsCorrect_ThrowsNoException()
 {
     MagickNET.SetTempDirectory(Path.GetTempPath());
 }
                public void ShouldReturnNullWhenFormatCannotBeDetermined()
                {
                    var formatInfo = MagickNET.GetFormatInformation(new byte[] { 42 });

                    Assert.Null(formatInfo);
                }
                public void ShouldThrowExceptionWhenArrayIsEmpty()
                {
                    var exception = Assert.Throws <ArgumentException>(() => MagickNET.GetFormatInformation(Array.Empty <byte>()));

                    Assert.Equal("data", exception.ParamName);
                }
                public void ShouldThrowExceptionWhenArrayIsNull()
                {
                    var exception = Assert.Throws <ArgumentNullException>(() => MagickNET.GetFormatInformation((byte[])null));

                    Assert.Equal("data", exception.ParamName);
                }
                public void ShouldReturnNullForUnknownFormat()
                {
                    var formatInfo = MagickNET.GetFormatInformation((MagickFormat)12345);

                    Assert.Null(formatInfo);
                }
예제 #27
0
        private static System.Drawing.Image EnchanceDPI(System.Drawing.Image DPIImage)
        {
            //Bitmap currentImage = new Bitmap(ImageDirectory);
            //Bitmap cleanImage = CleanText.Resize(currentImage, currentImage.Width, currentImage.Height);
            //using (MagickImage img = new MagickImage(cleanImage))
            //{
            //    img.Write("ManualImage.tif");
            //}


            //  QuantizeSettings qs = new QuantizeSettings();

            // qs.ColorSpace = ColorSpace.Gray;
            // image.Quantize(qs);
            //image.ColorType = ColorType.Grayscale;
            //image.ContrastStretch(new Percentage(0), new Percentage(0));

            //QuantizeSettings qs2 = new QuantizeSettings();
            //image.Negate();
            //qs2.ColorSpace = ColorSpace.GRAY;
            //image.Quantize(qs2);

            //image.ColorType = ColorType.Grayscale;
            //image.AdaptiveThreshold(30, 30, 10);
            //  image.BackgroundColor = Color.White;
            //image.AdaptiveThreshold(15, 15, 10);
            //image.ContrastStretch(0, 0);
            //ImageOptimizer optimizer = new ImageOptimizer();
            //optimizer.LosslessCompress(image.FileName);

            // image.Negate();

            MagickNET.Initialize(@"C:\OCR\File\");
            // Read first frame of gif image
            using (MagickImage image = new MagickImage("Snakeware.gif"))
            {
                image.Density = new PointD(600, 600);
                image.AutoLevel();
                image.Negate();
                image.AdaptiveThreshold(30, 30, 10);
                image.Negate();
                image.Write("Snakeware.jpg");
            }

            // Write to stream
            MagickReadSettings settings = new MagickReadSettings();

            // Tells the xc: reader the image to create should be 800x600
            settings.Width  = 800;
            settings.Height = 600;
            //settings.Density = 600;
            using (MemoryStream memStream = new MemoryStream())
            {
                // Create image that is completely purple and 800x600
                using (MagickImage image = new MagickImage("xc:purple", settings))
                {
                    // Sets the output format to png
                    image.Format = MagickFormat.Png;
                    // Write the image to the memorystream
                    image.Write(memStream);
                }
            }
            return(DPIImage);
        }
예제 #28
0
 public static void Initialize(TestContext context)
 {
     MagickNET.SetGhostscriptDirectory(@"C:\Program Files (x86)\gs\gs9.20\bin");
 }
예제 #29
0
        public void Test_Properties()
        {
            MagickFormatInfo formatInfo = MagickNET.GetFormatInformation(MagickFormat.Gradient);

            Assert.IsNotNull(formatInfo);
            Assert.AreEqual(MagickFormat.Gradient, formatInfo.Format);
            Assert.AreEqual(true, formatInfo.CanReadMultithreaded);
            Assert.AreEqual(true, formatInfo.CanWriteMultithreaded);
            Assert.AreEqual("Gradual linear passing from one shade to another", formatInfo.Description);
            Assert.AreEqual(false, formatInfo.IsMultiFrame);
            Assert.AreEqual(true, formatInfo.IsReadable);
            Assert.AreEqual(false, formatInfo.IsWritable);
            Assert.AreEqual(null, formatInfo.MimeType);

            formatInfo = MagickNET.GetFormatInformation(MagickFormat.Jp2);
            Assert.IsNotNull(formatInfo);
            Assert.AreEqual(MagickFormat.Jp2, formatInfo.Format);
            Assert.AreEqual(true, formatInfo.CanReadMultithreaded);
            Assert.AreEqual(true, formatInfo.CanWriteMultithreaded);
            Assert.AreEqual("JPEG-2000 File Format Syntax", formatInfo.Description);
            Assert.AreEqual(false, formatInfo.IsMultiFrame);
            Assert.AreEqual(true, formatInfo.IsReadable);
            Assert.AreEqual(true, formatInfo.IsWritable);
            Assert.AreEqual("image/jp2", formatInfo.MimeType);

            formatInfo = MagickNET.GetFormatInformation(MagickFormat.Jpg);
            Assert.IsNotNull(formatInfo);
            Assert.AreEqual(true, formatInfo.CanReadMultithreaded);
            Assert.AreEqual(true, formatInfo.CanWriteMultithreaded);
            Assert.AreEqual("Joint Photographic Experts Group JFIF format", formatInfo.Description);
            Assert.AreEqual(MagickFormat.Jpg, formatInfo.Format);
            Assert.AreEqual(false, formatInfo.IsMultiFrame);
            Assert.AreEqual(true, formatInfo.IsReadable);
            Assert.AreEqual(true, formatInfo.IsWritable);
            Assert.AreEqual("image/jpeg", formatInfo.MimeType);
            Assert.AreEqual(MagickFormat.Jpeg, formatInfo.Module);

            formatInfo = MagickNET.GetFormatInformation(MagickFormat.Png);
            Assert.IsNotNull(formatInfo);
            Assert.AreEqual(true, formatInfo.CanReadMultithreaded);
            Assert.AreEqual(true, formatInfo.CanWriteMultithreaded);
            Assert.AreEqual("Portable Network Graphics", formatInfo.Description);
            Assert.AreEqual(MagickFormat.Png, formatInfo.Format);
            Assert.AreEqual(false, formatInfo.IsMultiFrame);
            Assert.AreEqual(true, formatInfo.IsReadable);
            Assert.AreEqual(true, formatInfo.IsWritable);
            Assert.AreEqual("image/png", formatInfo.MimeType);
            Assert.AreEqual(MagickFormat.Png, formatInfo.Module);

            formatInfo = MagickNET.GetFormatInformation(MagickFormat.Xps);
            Assert.IsNotNull(formatInfo);
            Assert.AreEqual(false, formatInfo.CanReadMultithreaded);
            Assert.AreEqual(false, formatInfo.CanWriteMultithreaded);
            Assert.AreEqual("Microsoft XML Paper Specification", formatInfo.Description);
            Assert.AreEqual(MagickFormat.Xps, formatInfo.Format);
            Assert.AreEqual(false, formatInfo.IsMultiFrame);
            Assert.AreEqual(true, formatInfo.IsReadable);
            Assert.AreEqual(false, formatInfo.IsWritable);
            Assert.IsNull(formatInfo.MimeType);
            Assert.AreEqual(MagickFormat.Xps, formatInfo.Module);
        }
                public void ShouldThrowExceptionWhenFileMameIsNull()
                {
                    var exception = Assert.Throws <ArgumentNullException>(() => MagickNET.GetFormatInformation((string)null));

                    Assert.Equal("fileName", exception.ParamName);
                }