示例#1
3
    public static void CreateAnimatedGif()
    {
      using (MagickImageCollection collection = new MagickImageCollection())
      {
        // Add first image and set the animation delay to 100ms
        collection.Add(SampleFiles.SnakewarePng);
        collection[0].AnimationDelay = 100;

        // Add second image, set the animation delay to 100ms and flip the image
        collection.Add(SampleFiles.SnakewarePng);
        collection[1].AnimationDelay = 100;
        collection[1].Flip();

        // Optionally reduce colors
        QuantizeSettings settings = new QuantizeSettings();
        settings.Colors = 256;
        collection.Quantize(settings);

        // Optionally optimize the images (images should have the same size).
        collection.Optimize();

        // Save gif
        collection.Write(SampleFiles.OutputDirectory + "Snakeware.Animated.gif");
      }
    }
    public void Test_Collection_Read()
    {
      using (MagickImageCollection collection = new MagickImageCollection())
      {
        MagickReadSettings settings = new MagickReadSettings();
        settings.Density = new Density(150);

        collection.Read(Files.RoseSparkleGIF, settings);

        Assert.AreEqual(150, collection[0].Density.X);

        settings = new MagickReadSettings();
        settings.FrameIndex = 1;

        collection.Read(Files.RoseSparkleGIF, settings);

        Assert.AreEqual(1, collection.Count);

        settings = new MagickReadSettings();
        settings.FrameIndex = 1;
        settings.FrameCount = 2;

        collection.Read(Files.RoseSparkleGIF, settings);

        Assert.AreEqual(2, collection.Count);

        settings = null;
        collection.Read(Files.RoseSparkleGIF, settings);
      }
    }
示例#3
0
文件: PdfCov.cs 项目: Centny/cswf.doc
 public override void Exec()
 {
     //var pages = this.Beg;
     L.D("executing pdf2img by file({0}),destination format({1})", this.AsSrc, this.AsDstF);
     this.Cdl.add();
     var tf_base = Path.GetTempFileName();
     var tf = tf_base + Path.GetExtension(this.AsSrc);
     MagickImageCollection images = new MagickImageCollection();
     try
     {
         File.Copy(this.AsSrc, tf, true);
         this.Pdf2imgProc(images, tf, -1, 0);
     }
     catch (Exception e)
     {
         L.E(e, "executing pdf2img by file({0}),destination format({1}) fail with error->{2}", tf, this.AsDstF, e.Message);
         this.Result.Code = 500;
         this.Fails.Add(e);
     }
     try
     {
         File.Delete(tf);
         File.Delete(tf_base);
     }
     catch (Exception e)
     {
         L.W("executing pdf2img on delete temp file({0}) error->{1}", tf, e.Message);
     }
     this.Cdl.done();
     this.Cdl.wait();
     images.Dispose();
     L.D("executing pdf2img by file({0}),destination format({1}) done with pages({2}),fails({3})", this.AsSrc, this.AsDstF, this.Result.Count, this.Fails.Count);
 }
    public void Test_Append()
    {
      int width = 70;
      int height = 46;

      using (MagickImageCollection collection = new MagickImageCollection())
      {
        ExceptionAssert.Throws<InvalidOperationException>(delegate ()
        {
          collection.AppendHorizontally();
        });

        ExceptionAssert.Throws<InvalidOperationException>(delegate ()
        {
          collection.AppendVertically();
        });

        collection.Read(Files.RoseSparkleGIF);

        Assert.AreEqual(width, collection[0].Width);
        Assert.AreEqual(height, collection[0].Height);

        using (MagickImage image = collection.AppendHorizontally())
        {
          Assert.AreEqual(width * 3, image.Width);
          Assert.AreEqual(height, image.Height);
        }

        using (MagickImage image = collection.AppendVertically())
        {
          Assert.AreEqual(width, image.Width);
          Assert.AreEqual(height * 3, image.Height);
        }
      }
    }
        public override void ConfigGA(GeneticAlgorithm ga)
        {
            base.ConfigGA(ga);
            ga.MutationProbability = 0.4f;
            ga.TerminationReached += (sender, args) =>
            {
                using (var collection = new MagickImageCollection())
                {
                    var files = Directory.GetFiles(m_destFolder, "*.png");

                    foreach (var image in files)
                    {
                        collection.Add(image);
                        collection[0].AnimationDelay = 100;
                    }

                    var settings = new QuantizeSettings();
                    settings.Colors = 256;
                    collection.Quantize(settings);

                    collection.Optimize();
                    collection.Write(Path.Combine(m_destFolder, "result.gif"));
                }
            };
        }
示例#6
0
    public static void ConvertPDFTOneImage()
    {
      MagickReadSettings settings = new MagickReadSettings();
      // Settings the density to 300 dpi will create an image with a better quality
      settings.Density = new PointD(300, 300);

      using (MagickImageCollection images = new MagickImageCollection())
      {
        // Add all the pages of the pdf file to the collection
        images.Read(SampleFiles.SnakewarePdf, settings);

        // Create new image that appends all the pages horizontally
        using (MagickImage horizontal = images.AppendHorizontally())
        {
          // Save result as a png
          horizontal.Write(SampleFiles.OutputDirectory + "Snakeware.horizontal.png");
        }

        // Create new image that appends all the pages horizontally
        using (MagickImage vertical = images.AppendVertically())
        {
          // Save result as a png
          vertical.Write(SampleFiles.OutputDirectory + "Snakeware.vertical.png");
        }
      }
    }
示例#7
0
文件: PdfCov.cs 项目: Centny/cswf.doc
 protected virtual int Pdf2imgProc(MagickImageCollection images, String pdf, int idx, int file_c)
 {
     images.Read(pdf, settings);
     int pages = images.Count;
     if (pages > this.MaxPage)
     {
         this.Result.Code = 413;
         L.D("executing pdf2img by file({0}),destination format({1}) fail with too large code({2}),count({3})",
             this.AsSrc, this.AsDstF, this.Result.Code, this.Result.Count);
         return 0;
     }
     if (idx < 0)
     {
         this.Total = new int[pages];
         this.Done = new int[pages];
         Util.set(this.Total, 1);
         Util.set(this.Done, 0);
     }
     else
     {
         this.Total[idx] = pages;
     }
     for (var i = 0; i < pages; i++)
     {
         this.Pdf2imgProc(images[i], idx, i, file_c);
     }
     return pages;
 }
 private static void Test_Read(MagickImageCollection collection)
 {
   Assert.AreEqual(3, collection.Count);
   foreach (MagickImage image in collection)
   {
     Assert.AreEqual(70, image.Width);
     Assert.AreEqual(46, image.Height);
   }
 }
    private static void WriteAndCheckProfile(MagickImageCollection images, PsdWriteDefines defines, int expectedLength)
    {
      using (MemoryStream memStream = new MemoryStream())
      {
        images.Write(memStream, defines);

        memStream.Position = 0;
        images.Read(memStream);
        CheckProfile(images[1], expectedLength);
      }
    }
    public void Test_ToBitmap()
    {
      using (MagickImageCollection collection = new MagickImageCollection(Files.RoseSparkleGIF))
      {
        Assert.AreEqual(3, collection.Count);

        Bitmap bitmap = collection.ToBitmap();
        Assert.IsNotNull(bitmap);
        Assert.AreEqual(3, bitmap.GetFrameCount(FrameDimension.Page));
      }
    }
示例#11
0
    private MagickImage CreatePallete()
    {
      using (MagickImageCollection images = new MagickImageCollection())
      {
        images.Add(new MagickImage(MagickColors.Red, 1, 1));
        images.Add(new MagickImage(MagickColors.Blue, 1, 1));
        images.Add(new MagickImage(MagickColors.Green, 1, 1));

        return images.AppendHorizontally();
      }
    }
    private static void Test_Ping(MagickImageCollection collection)
    {
      Assert.AreEqual(1, collection.Count);

      ExceptionAssert.Throws<InvalidOperationException>(delegate ()
      {
        collection[0].GetPixels();
      });

      ImageProfile profile = collection[0].Get8BimProfile();
      Assert.IsNotNull(profile);
    }
示例#13
0
    public static void CreatePDFFromTwoImages()
    {
      using (MagickImageCollection collection = new MagickImageCollection())
      {
        // Add first page
        collection.Add(new MagickImage(SampleFiles.SnakewareJpg));
        // Add second page
        collection.Add(new MagickImage(SampleFiles.SnakewareJpg));

        // Create pdf file with two pages
        collection.Write(SampleFiles.OutputDirectory + "Snakeware.pdf");
      }
    }
    public void Test_Collection_Exceptions()
    {
      using (MagickImageCollection collection = new MagickImageCollection())
      {
        MagickReadSettings settings = new MagickReadSettings();
        settings.PixelStorage = new PixelStorageSettings();

        ExceptionAssert.Throws<ArgumentException>(delegate ()
        {
          collection.Read(Files.RoseSparkleGIF, settings);
        });
      }
    }
示例#15
0
 public void CreateIconFromPngFilesFromSvg(IconInfo iconInfo)
 {
     if (iconInfo.NeedUpdate())
     {
         using (var imageCollection = new MagickImageCollection())
         {
             foreach (var iconInfoPngFile in iconInfo.PngFiles)
             {
                 var image = new MagickImage(iconInfoPngFile.FullName);
                 imageCollection.Add(image);
             }
             imageCollection.Write(iconInfo.IconFile.FullName);
         }
     }            
 }
        public void Convert2Jpeg(bool rotate = false)
        {
            try
            {
                MagickReadSettings settings = new MagickReadSettings();

                // Settings the density to 300 dpi will create an image with a better quality
                settings.Density = new PointD(300, 300);

                using (MagickImageCollection images = new MagickImageCollection())
                {
                    // Add all the pages of the pdf file to the collection
                    images.Read(_pdf.FullName, settings);

                    if (images.Count > 0 && images[0].Format == MagickFormat.Pdf)
                    {
                        _logger.InfoFormat("Handle {0}", _pdf.FullName);

                        int page = 1;
                        foreach (MagickImage image in images)
                        {
                            var newFileName = GetFilePageName(page) + ".jpg";

                            // Need page rotation?
                            if (rotate)
                                image.Rotate(90.0);

                            // Write page to file that contains the page number
                            image.Format = MagickFormat.Jpg;
                            image.CompressionMethod = CompressionMethod.JPEG;
                            image.Quality = 75;
                            image.Write(newFileName);

                            _logger.InfoFormat("-> {0}", newFileName);

                            // Writing to a specific format works the same as for a single image
                            page++;
                        }
                    }
                }

            }
            catch (Exception ex)
            {
                _logger.Error(ex.Message, ex);
            }
        }
 public int SplitIco(string icoFileName)
 {
     var fullName = Path.GetFullPath(icoFileName);
     var folder = Path.GetDirectoryName(fullName);
     var baseName = Path.GetFileNameWithoutExtension(fullName);
     using (var imageCollection = new MagickImageCollection())
     {
         imageCollection.Read(icoFileName);
         foreach (var image in imageCollection)
         {                    
             var pngFileName = baseName + "-" + image.Height + ".png";
             var pngFile = Path.Combine(folder, pngFileName);
             image.Write(pngFile);
         }
     }
     return 0;
 }
    public void Test_AddRange()
    {
      using (MagickImageCollection collection = new MagickImageCollection(Files.RoseSparkleGIF))
      {
        Assert.AreEqual(3, collection.Count);

        collection.AddRange(Files.RoseSparkleGIF);
        Assert.AreEqual(6, collection.Count);

        collection.AddRange(collection);
        Assert.AreEqual(12, collection.Count);

        List<MagickImage> images = new List<MagickImage>();
        images.Add(new MagickImage("xc:red", 100, 100));
        collection.AddRange(images);
        Assert.AreEqual(13, collection.Count);
      }
    }
示例#19
0
		private static void ConvertPdfToOneTif()
		{
			// Log all events
			//MagickNET.SetLogEvents(LogEvents.All | LogEvents.Trace);
			// Set the log handler (all threads use the same handler)
			//MagickNET.Log += DetailedDebugInformationSamples.MagickNET_Log;

			string sampleDocsDirectory = @"E:\projects\ImageProcessing\sampledocs\";
			string sampleFile = "sample6.pdf";

			try
			{
				MagickReadSettings settings = new MagickReadSettings();
				settings.Density = new PointD(300, 300);

				using (MagickImageCollection images = new MagickImageCollection())
				{
					// Add all the pages of the source file to the collection
					images.Read(Path.Combine(sampleDocsDirectory, sampleFile), settings);

					//Show page count
					Console.WriteLine("page count for {0} {1}", sampleFile, images.Count);

					string baseFileName = Path.GetFileNameWithoutExtension(sampleFile);

					// Create new image that appends all the pages horizontally
					//using (MagickImage vertical = images.AppendVertically())
					//{
					//	vertical.CompressionMethod = CompressionMethod.Group4;
					//	Console.WriteLine("saving file: {0}", baseFileName + ".tif");
					//	vertical.Write(sampleDocsDirectory + baseFileName + ".tif");
					//}

					Console.WriteLine("saving file: {0}", baseFileName + ".tif");
					images.Write(sampleDocsDirectory + baseFileName + ".tif");
				}

			}
			catch (Exception ex)
			{
				Console.WriteLine("ConvertPdfToOneTif {0}", ex.Message);
			}
		}
示例#20
0
    public static void MergeMultipleImages()
    {
      using (MagickImageCollection images = new MagickImageCollection())
      {
        // Add the first image
        MagickImage first = new MagickImage(SampleFiles.SnakewarePng);
        images.Add(first);

        // Add the second image
        MagickImage second = new MagickImage(SampleFiles.SnakewarePng);
        images.Add(second);

        // Create a mosaic from both images
        using (MagickImage result = images.Mosaic())
        {
          // Save the result
          result.Write(SampleFiles.OutputDirectory + "Mosaic.png");
        }
      }
    }
示例#21
0
    public static void ResizeAnimatedGif()
    {
      // Read from file
      using (MagickImageCollection collection = new MagickImageCollection(SampleFiles.SnakewareGif))
      {
        // This will remove the optimization and change the image to how it looks at that point
        // during the animation. More info here: http://www.imagemagick.org/Usage/anim_basics/#coalesce
        collection.Coalesce();

        // Resize each image in the collection to a width of 200. When zero is specified for the height
        // the height will be calculated with the aspect ratio.
        foreach (MagickImage image in collection)
        {
          image.Resize(200, 0);
        }

        // Save the result
        collection.Write(SampleFiles.OutputDirectory + "Snakeware.resized.gif");
      }
    }
示例#22
0
        /// <summary>
        /// Returns a decoded image from ImageMagick - assumes only a singal frame,
        /// as many methods I need are internal to ImageSharp
        /// </summary>
        /// <typeparam name="TPixel"></typeparam>
        /// <param name="configuration"></param>
        /// <param name="stream"></param>
        /// <returns></returns>
        public Image <TPixel> Decode <TPixel>(Configuration configuration, Stream stream)
            where TPixel : unmanaged, SixLabors.ImageSharp.PixelFormats.IPixel <TPixel>
        {
            var settings = new Magick.MagickReadSettings();

            using var magickImageCollection = new Magick.MagickImageCollection(stream, settings);

            if (magickImageCollection.Count == 0)
            {
                throw new Exception("No images found");
            }

            Magick.IMagickImage <ushort> magickImage = magickImageCollection[0];
            var width  = magickImage.Width;
            var height = magickImage.Height;

            var image = new Image <TPixel>(configuration, width, height);


            var framePixels = image.GetPixelMemoryGroup();


            using Magick.IUnsafePixelCollection <ushort> pixels = magickImage.GetPixelsUnsafe();
            if (magickImage.Depth == 8 || magickImage.Depth == 6 || magickImage.Depth == 4 || magickImage.Depth == 2 || magickImage.Depth == 1 || magickImage.Depth == 10 || magickImage.Depth == 12)
            {
                byte[]? data = pixels.ToByteArray(Magick.PixelMapping.RGBA);

                FromRgba32Bytes(configuration, data, framePixels);
            }
            else if (magickImage.Depth == 16 || magickImage.Depth == 14)
            {
                ushort[]? data = pixels.ToShortArray(Magick.PixelMapping.RGBA);
                Span <byte> bytes = MemoryMarshal.Cast <ushort, byte>(data.AsSpan());
                FromRgba64Bytes(configuration, bytes, framePixels);
            }
            else
            {
                throw new InvalidOperationException();
            }
            return(image);
        }
示例#23
0
        public void saveResult(string FilePath1, string FilePath2, string outFilePath)
        {
            MagickImageCollection images = new MagickImageCollection();
            // Add the first image
            MagickImage first = new MagickImage(FilePath1);

             //   images.Add(first);

            // Add the second image
            MagickImage second = new MagickImage(FilePath2);
               // images.Add(second);

            /*
            first.Composite(second, 0, 0, CompositeOperator.ModulusAdd);
            first.Write(outFilePath + "compos.png");

            */
            MagickImage third = new MagickImage();
            first.Compare(second, ErrorMetric.Absolute, third);
            third.Write(outFilePath + "third.bmp");
        }
示例#24
0
        private MagickImage ExecuteCombine(XmlElement element, MagickImageCollection collection)
        {
            Hashtable arguments = new Hashtable();

            foreach (XmlAttribute attribute in element.Attributes)
            {
                arguments[attribute.Name] = Variables.GetValue <Channels>(attribute);
            }
            if (arguments.Count == 0)
            {
                return(collection.Combine());
            }
            else if (OnlyContains(arguments, "channels"))
            {
                return(collection.Combine((Channels)arguments["channels"]));
            }
            else
            {
                throw new ArgumentException("Invalid argument combination for 'combine', allowed combinations are: [] [channels]");
            }
        }
示例#25
0
    public void Test_AdditionalInfo()
    {

      using (MagickImageCollection images = new MagickImageCollection())
      {
        images.Read(Files.Coders.LayerStylesSamplePSD);

        CheckProfile(images[1], 264);

        var defines = new PsdWriteDefines()
        {
          AdditionalInfo = PsdAdditionalInfo.All
        };
        WriteAndCheckProfile(images, defines, 264);

        defines.AdditionalInfo = PsdAdditionalInfo.Selective;
        WriteAndCheckProfile(images, defines, 152);

        defines.AdditionalInfo = PsdAdditionalInfo.None;
        WriteAndCheckProfile(images, defines, 0);
      }
    }
示例#26
0
        private MagickImage ExecuteQuantize(XmlElement element, MagickImageCollection collection)
        {
            Hashtable arguments = new Hashtable();

            foreach (XmlElement elem in element.SelectNodes("*"))
            {
                arguments[elem.Name] = CreateQuantizeSettings(elem);
            }
            if (arguments.Count == 0)
            {
                collection.Quantize();
                return(null);
            }
            else if (OnlyContains(arguments, "settings"))
            {
                collection.Quantize((QuantizeSettings)arguments["settings"]);
                return(null);
            }
            else
            {
                throw new ArgumentException("Invalid argument combination for 'quantize', allowed combinations are: [] [settings]");
            }
        }
示例#27
0
    public static void ConvertPDFToMultipleImages()
    {
      MagickReadSettings settings = new MagickReadSettings();
      // Settings the density to 300 dpi will create an image with a better quality
      settings.Density = new PointD(300, 300);

      using (MagickImageCollection images = new MagickImageCollection())
      {
        // Add all the pages of the pdf file to the collection
        images.Read(SampleFiles.SnakewarePdf, settings);

        int page = 1;
        foreach (MagickImage image in images)
        {
          // Write page to file that contains the page number
          image.Write(SampleFiles.OutputDirectory + "Snakeware.Page" + page + ".png");
          // Writing to a specific format works the same as for a single image
          image.Format = MagickFormat.Ptif;
          image.Write(SampleFiles.OutputDirectory + "Snakeware.Page" + page + ".tif");
          page++;
        }
      }
    }
    public void Test_Append()
    {
      int width = 70;
      int height = 46;

      using (MagickImageCollection collection = new MagickImageCollection(Files.RoseSparkleGIF))
      {
        Assert.AreEqual(width, collection[0].Width);
        Assert.AreEqual(height, collection[0].Height);

        using (MagickImage image = collection.AppendHorizontally())
        {
          Assert.AreEqual(width * 3, image.Width);
          Assert.AreEqual(height, image.Height);
        }

        using (MagickImage image = collection.AppendVertically())
        {
          Assert.AreEqual(width, image.Width);
          Assert.AreEqual(height * 3, image.Height);
        }
      }
    }
示例#29
0
        public static void Run(string oldFilePath, string newFilePath, int width, int height, int? quality)
        {
            if (!oldFilePath.EndsWith("gif", StringComparison.OrdinalIgnoreCase))
            {
                using (var image = new MagickImage(oldFilePath))
                {
                    Process(width, height, image, quality);
                    image.Write(newFilePath);
                }
            }
            else
            {
                using (var collection = new MagickImageCollection(oldFilePath))
                {

                    foreach (var image in collection)
                    {
                        Process(width, height, image, quality);
                    }
                    collection.Write(newFilePath);
                }
            }
        }
        public void ConvertToGrayScale(string sourceFile, string targetFile)
        {
            using (MagickImageCollection images = new MagickImageCollection())
            {
                string newTargetFile = @"D:\Development\Magik\Images\NewTiffs\New.tif";
                MagickReadSettings settings = new MagickReadSettings();
                images.Read(sourceFile, settings);
                settings.FrameIndex = 0; // First page
                settings.FrameCount = images.Count; // Number of pages
                int count = images.Count;

                foreach (MagickImage image in images)
                {
                    image.ColorType = ColorType.Grayscale;
                    image.Quantize();

                    image.Write(newTargetFile + count.ToString() + ".tif");
                    ++count;
                }
            }

            Process proc = new Process
            {
                StartInfo = new ProcessStartInfo

                {

                    FileName = @"C:\Program Files (x86)\ImageMagick-6.8.6-Q8\convert.exe",
                    Arguments = @"D:\Development\Magik\Images\NewTiffs\*.tif D:\Development\Magik\Images\Combined\all-in-one.tif",
                    UseShellExecute = false,
                    RedirectStandardError = true,
                    CreateNoWindow = true
                }
            };

            proc.Start();
        }
示例#31
0
        ///<summary>
        /// Create a composite image by combining the images with the specified settings.
        ///</summary>
        ///<param name="settings">The settings to use.</param>
        ///<exception cref="MagickException"/>
        public MagickImage Montage(MontageSettings settings)
        {
            ThrowIfEmpty();

            Throw.IfNull("settings", settings);

            IntPtr images;

            try
            {
                AttachImages();
                if (!string.IsNullOrEmpty(settings.Label))
                {
                    _Images[0].Label = settings.Label;
                }
                images = _NativeInstance.Montage(_Images[0], settings);
            }
            finally
            {
                DetachImages();
            }

            using (MagickImageCollection collection = new MagickImageCollection())
            {
                collection.AddRange(MagickImage.CreateList(images, _Images[0].Settings));
                if (settings.TransparentColor != null)
                {
                    foreach (MagickImage image in collection)
                    {
                        image.Transparent(settings.TransparentColor);
                    }
                }

                return(collection.Merge());
            }
        }
示例#32
0
        public ActionResult UploadFile(HttpPostedFileBase file, Guid id)
        {
            var stage = Db.CandidatureStages.SingleOrDefault(x => x.Id == id);

            if (file == null || stage == null)
            {
                return(null);
            }

            var maxSize = 1920;

            var images = new ImageMagick.MagickImageCollection(file.InputStream);

            if (images.Count < 1)
            {
                return(null);
            }


            var width_org  = images[0].Width;
            var height_org = images[0].Height;


            foreach (var image in images)
            {
                if (image.Width > maxSize || image.Height > maxSize)
                {
                    image.Resize(new MagickGeometry(widthAndHeight: maxSize));
                }
            }


            var width  = images[0].Width;
            var height = images[0].Height;

            var bytes      = images.ToByteArray();
            var length     = bytes.Length;
            var length_org = file.ContentLength;
            var ratio      = length / (double)length_org;

            var material = new CandidatureStageMaterial
            {
                Stage = stage,
            };

            Db.CandidatureStageMaterial.Add(material);

            var storage = new BinaryStorage
            {
                Category    = "Material",
                FileType    = file.ContentType,
                BinaryData  = bytes,
                Created     = DateTime.Now,
                Name        = string.Empty,
                Description =
                    $"Original: [{width_org}x{height_org} ({length_org})], Gespeichert: [{width}x{height} ({length})], Verhältnis zu Original: [{ratio:P0}], Anzahl Ebenen: [{images.Count}]"
            };

//            file.InputStream.Read(storage.BinaryData, 0, file.ContentLength);


            Db.Storages.Add(storage);

            material.Storage = storage;

            Db.SaveChanges();

            return(null);
        }
示例#33
0
 private static MagickImage ExecuteTrimBounds(MagickImageCollection collection)
 {
     collection.TrimBounds();
     return(null);
 }
示例#34
0
        private MagickImage ExecuteFx(XmlElement element, MagickImageCollection collection)
        {
            String expression_ = Variables.GetValue <String>(element, "expression");

            return(collection.Fx(expression_));
        }
示例#35
0
        private MagickImage ExecuteCollection(XmlElement element, MagickImageCollection collection)
        {
            switch (element.Name[0])
            {
            case 'c':
            {
                switch (element.Name[2])
                {
                case 'a':
                {
                    return(ExecuteCoalesce(collection));
                }

                case 'm':
                {
                    return(ExecuteCombine(element, collection));
                }
                }
                break;
            }

            case 'd':
            {
                return(ExecuteDeconstruct(collection));
            }

            case 'm':
            {
                switch (element.Name[1])
                {
                case 'a':
                {
                    return(ExecuteMap(element, collection));
                }

                case 'o':
                {
                    switch (element.Name[2])
                    {
                    case 'r':
                    {
                        return(ExecuteMorph(element, collection));
                    }

                    case 'n':
                    {
                        return(ExecuteMontage(element, collection));
                    }

                    case 's':
                    {
                        return(ExecuteMosaic(collection));
                    }
                    }
                    break;
                }

                case 'e':
                {
                    return(ExecuteMerge(collection));
                }
                }
                break;
            }

            case 'o':
            {
                if (element.Name.Length == 8)
                {
                    return(ExecuteOptimize(collection));
                }
                switch (element.Name[8])
                {
                case 'P':
                {
                    return(ExecuteOptimizePlus(collection));
                }

                case 'T':
                {
                    return(ExecuteOptimizeTransparency(collection));
                }
                }
                break;
            }

            case 'q':
            {
                return(ExecuteQuantize(element, collection));
            }

            case 'r':
            {
                switch (element.Name[2])
                {
                case 'P':
                {
                    return(ExecuteRePage(collection));
                }

                case 'v':
                {
                    return(ExecuteReverse(collection));
                }
                }
                break;
            }

            case 't':
            {
                return(ExecuteTrimBounds(collection));
            }

            case 'a':
            {
                switch (element.Name[6])
                {
                case 'H':
                {
                    return(ExecuteAppendHorizontally(collection));
                }

                case 'V':
                {
                    return(ExecuteAppendVertically(collection));
                }
                }
                break;
            }

            case 'e':
            {
                return(ExecuteEvaluate(element, collection));
            }

            case 'f':
            {
                return(ExecuteFlatten(collection));
            }

            case 's':
            {
                switch (element.Name[5])
                {
                case 'H':
                {
                    return(ExecuteSmushHorizontal(element, collection));
                }

                case 'V':
                {
                    return(ExecuteSmushVertical(element, collection));
                }
                }
                break;
            }
            }
            throw new NotSupportedException(element.Name);
        }
示例#36
0
 private static MagickImage ExecuteTrimBounds(MagickImageCollection collection)
 {
     return(collection.TrimBounds());
 }
示例#37
0
 private static MagickImage ExecuteOptimizeTransparency(MagickImageCollection collection)
 {
     collection.OptimizeTransparency();
     return(null);
 }
示例#38
0
 private static MagickImage ExecuteAppendVertically(MagickImageCollection collection)
 {
     return(collection.AppendVertically());
 }
示例#39
0
 private static MagickImage ExecuteMerge(MagickImageCollection collection)
 {
     return(collection.Merge());
 }
示例#40
0
 private static MagickImage ExecuteCoalesce(MagickImageCollection collection)
 {
     collection.Coalesce();
     return(null);
 }
示例#41
0
        // Load images from twitter, process them into collage
        string ImageProcessing(List<string> urls, int size, List<int> counts, bool resize)
        {
            byte[] imageByteData = null;
            byte[] data = null;
            // Load images into collection
            using (MagickImageCollection collection = new MagickImageCollection())
            {
                
                for (int i = 0; i < urls.Count; i++)
                {
                    imageByteData = new System.Net.WebClient().DownloadData(urls[i]);
                    MagickImage tmpImage = new MagickImage(imageByteData);
                    collection.Add(tmpImage);
                }
                // generade byte array for collage from images collection
                if (resize)
                {
                    // collage with proportional images
                    SizableImages simages = new SizableImages(counts);
                    List<SizableImage> arrangedImages = simages.GetImages();
                    int width = simages.GetXBottom() - simages.GetXTop();
                    int height = simages.GetYBottom() - simages.GetYTop();

                    int maxDimension;

                    if (width < height)
                    {
                        maxDimension = height;
                    }
                    else
                    {
                        maxDimension = width;
                    }

                    double correction = (double)size / maxDimension;


                    MagickReadSettings settings = new MagickReadSettings();
                    settings.Width = (int)(width * correction);
                    settings.Height = (int)(height * correction);
                    using (MagickImage image = new MagickImage("xc:white", settings))
                    {
                        for (int i = 0; i < arrangedImages.Count(); i++)
                        {
                            collection[
                                arrangedImages[i].id
                                ].Resize(new MagickGeometry((int)(arrangedImages[i].size * correction)));
                            image.Composite(collection[arrangedImages[i].id],
                                (int)(arrangedImages[i].positionX * correction),
                                (int)(arrangedImages[i].positionY * correction));
                        }
                        image.Format = MagickFormat.Png;
                        data = image.ToByteArray();
                    }
                }
                else
                {
                    // collage with single sized images
                    data = GenerateCollage(collection, size);
                }
            }
            // convert byte array to data url
            string imageBase64Data = Convert.ToBase64String(data/*imageByteData*/);
            string imageDataURL = string.Format("data:image/png;base64,{0}", imageBase64Data);
            return imageDataURL;
        }
示例#42
0
        private MagickImage ExecuteEvaluate(XmlElement element, MagickImageCollection collection)
        {
            EvaluateOperator evaluateOperator_ = Variables.GetValue <EvaluateOperator>(element, "evaluateOperator");

            return(collection.Evaluate(evaluateOperator_));
        }
示例#43
0
 private static MagickImage ExecuteFlatten(MagickImageCollection collection)
 {
     return(collection.Flatten());
 }
示例#44
0
 private static MagickImage ExecuteReverse(MagickImageCollection collection)
 {
     collection.Reverse();
     return(null);
 }
示例#45
0
 private static MagickImage ExecuteOptimizePlus(MagickImageCollection collection)
 {
     collection.OptimizePlus();
     return(null);
 }
示例#46
0
 private static MagickImage ExecuteDeconstruct(MagickImageCollection collection)
 {
     collection.Deconstruct();
     return(null);
 }
示例#47
0
 private static MagickImage ExecuteMosaic(MagickImageCollection collection)
 {
     return(collection.Mosaic());
 }
示例#48
0
        private MagickImage ExecuteMontage(XmlElement element, MagickImageCollection collection)
        {
            MontageSettings settings_ = CreateMontageSettings(element["settings"]);

            return(collection.Montage(settings_));
        }
示例#49
0
		/**
		 * 指定されたディレクトリ内にある画像からGIFアニメーションを生成する
		 * @param {String} コマ画像が入っているディレクトリのパス
		 * @return {Boolean} 成功した場合はtrue
		 */
		Boolean GenerateAnimationGIF(String tmpDir, String dstPath) {
			String[] files = Directory.GetFiles(tmpDir);
			if (files.Length == 0) return false;
			using (MagickImageCollection collection = new MagickImageCollection()) {
				MagickImage canvas = new MagickImage(files[files.Length - 1]);
				canvas.AnimationDelay = 250;
				canvas.Scale((int)(canvas.Width * 0.5), (int)(canvas.Height * 0.5));
				collection.Add(canvas);

				int perFrame = (int)Math.Ceiling(600.0 / files.Length);
				foreach (String file in files) {
					canvas = new MagickImage(file);
					canvas.AnimationDelay = perFrame;
					canvas.Scale((int)(canvas.Width * 0.5), (int)(canvas.Height * 0.5));
					collection.Add(canvas);
				}

				collection.Optimize();
				collection.Write(dstPath);
			};
			return true;
		}
示例#50
0
        private MagickImage ExecuteSmushVertical(XmlElement element, MagickImageCollection collection)
        {
            Int32 offset_ = Variables.GetValue <Int32>(element, "offset");

            return(collection.SmushVertical(offset_));
        }
        /// <summary>
        /// Combines the screenshots into one contiguous screenshot
        /// </summary>
        /// <param name="files">The files (images) to combine</param>
        /// <param name="e">For UX, an output progress message</param>
        public static void CombineScreenshot(FileSystemInfo[] files, WaitWindowEventArgs e)
        {
           

            string screenshotLocation = Path.Combine(Constants.CacheLocation, "temp.png");

            using (MagickImageCollection images = new MagickImageCollection())
            {
                // Add the first image
                var orderedFiles = files.OrderBy(f => f.CreationTime);
                foreach (FileSystemInfo file in orderedFiles)
                {
                    MagickImage first = new MagickImage(file.FullName);
                    e.Window.Message = "Obtaining Snapshots... Please Wait";
                    images.Add(first);
                }

                using (MagickImage result = images.AppendVertically())
                {
                    e.Window.Message = "Building Screenshot... Please Wait" + System.Environment.NewLine + "This can take a minute.";
                    try
                    {
                        result.Write(screenshotLocation);
                    } catch (MagickImageErrorException err)
                    {
                        Debug.WriteLine($"Error: {err}");
                    }
                   
                }
        
            }
        }