Ejemplo n.º 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");
      }
    }
Ejemplo n.º 2
1
 private void SaveFile()
 {
     try
     {
         progress = 0;
         progressMax = (recorded.Count * 4);
         MagickImage[] mia = new MagickImage[recorded.Count];
         Parallel.For(0, recorded.Count, (i) =>
         {
             mia[i] = new MagickImage(recorded[i].Bitmap);
             int pr = Interlocked.Increment(ref progress);
             if (pr % 16 == 0) Invoke(new EmptyCallback(showProgress));
         });
         progressMax = progress + (mia.Length * 3);
         bool[] mid = new bool[mia.Length];
         mid[0] = false;
         Parallel.For(1, mia.Length, (i) =>
         {
             mid[i] = mia[i].Equals(mia[i - 1]);
             int pr = Interlocked.Increment(ref progress);
             if (pr % 4 == 0) Invoke(new EmptyCallback(showProgress));
         });
         Parallel.For(1, mia.Length, (i) =>
         {
             if (mid[i])
             {
                 mia[i].Dispose();
                 mia[i] = null;
             }
         });
         progressMax = progress + (mia.Length * 2);
         MagickImageCollection mic = new MagickImageCollection();
         QuantizeSettings qs = new QuantizeSettings();
         qs.Colors = 256;
         int timeOffset = 0;
         int addi = -1;
         for (int i = 0; i < mia.Length; ++i)
         {
             MagickImage mi = mia[i];
             int addDelay;
             if (mi != null)
             {
                 mic.Add(mi);
                 ++addi;
                 addDelay = 0;
             }
             else
             {
                 addDelay = mic[addi].AnimationDelay;
             }
             int delayMs = recorded[((i + 1) < recorded.Count) ? i + 1 : i].Time + timeOffset;
             int delayCs = delayMs / 10;
             timeOffset = delayMs - (delayCs * 10);
             mic[addi].AnimationDelay = delayCs + addDelay;
             ++progress;
             if (progress % 32 == 0) Invoke(new EmptyCallback(showProgress));
         }
         // mic.OptimizePlus();
         progressMax = progress + (mic.Count);
         Parallel.For(0, mic.Count, (i) =>
         {
             mic[i].Quantize(qs);
             int pr = Interlocked.Increment(ref progress);
             Invoke(new EmptyCallback(showProgress));
         });
         mic.Write(fileName);
         Parallel.For(0, mic.Count, (i) =>
         {
             mic[i].Dispose();
         });
         mic.Dispose();
         GC.Collect();
     }
     catch (Exception ex)
     {
         exc = ex;
     }
     Invoke(new EmptyCallback(doneSaving));
 }
Ejemplo n.º 3
0
    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);
      }
    }
Ejemplo n.º 4
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);
         }
     }            
 }
Ejemplo n.º 5
0
        private IMagickImage Execute(XmlElement element, MagickImageCollection collection)
        {
            if (element.Name == "read")
            {
                collection.Add(CreateMagickImage(element));
                return(null);
            }

            if (element.Name == "write")
            {
                string fileName_ = XmlHelper.GetAttribute <string>(element, "fileName");
                collection.Write(fileName_);
                return(null);
            }

            return(ExecuteCollection(element, collection));
        }
Ejemplo n.º 6
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);
			}
		}
Ejemplo n.º 7
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");
      }
    }
Ejemplo n.º 8
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);
                }
            }
        }
Ejemplo n.º 9
0
    private MagickImage Execute(XmlElement element, MagickImageCollection collection)
    {
      if (element.Name == "read")
      {
        collection.Add(CreateMagickImage(element));
        return null;
      }

      if (element.Name == "write")
      {
        string fileName_ = XmlHelper.GetAttribute<string>(element, "fileName");
        collection.Write(fileName_);
        return null;
      }

      return ExecuteCollection(element, collection);
    }
Ejemplo n.º 10
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;
		}
Ejemplo n.º 11
0
        private void saveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SaveFileDialog svd = new SaveFileDialog();
            svd.Filter = "GIF|*.gif";
            if (svd.ShowDialog() == DialogResult.OK)
            {
                using (MagickImageCollection collection = new MagickImageCollection())
                {
                    foreach (PictureBox pim in images)
                    {
                        collection.Add(new MagickImage((Bitmap)pim.Image.Clone()));
                        collection[collection.Count - 1].AnimationDelay = 100;
                    }

                    // 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(svd.FileName);
                }
            }
            else
            {
                svd.Dispose();
            }
        }
    public void Test_Write()
    {
      long fileSize;
      using (MagickImage image = new MagickImage(Files.RoseSparkleGIF))
      {
        fileSize = image.FileSize;
      }

      Assert.AreEqual(fileSize, 9891);

      using (MagickImageCollection collection = new MagickImageCollection(Files.RoseSparkleGIF))
      {
        using (MemoryStream memStream = new MemoryStream())
        {
          collection.Write(memStream);

          Assert.AreEqual(fileSize, memStream.Length);
        }
      }

      FileInfo tempFile = new FileInfo(Path.GetTempFileName() + ".gif");
      try
      {
        using (MagickImageCollection collection = new MagickImageCollection(Files.RoseSparkleGIF))
        {
          collection.Write(tempFile);

          Assert.AreEqual(fileSize, tempFile.Length);
        }
      }
      finally
      {
        if (tempFile.Exists)
          tempFile.Delete();
      }
    }
    public void Test_Write()
    {
      long fileSize;
      using (MagickImage image = new MagickImage(Files.Builtin.Rose))
      {
        fileSize = image.FileSize;
      }

      using (MagickImageCollection collection = new MagickImageCollection(Files.Builtin.Rose))
      {
        using (MemoryStream memStream = new MemoryStream())
        {
          collection.Write(memStream);

          Assert.AreEqual(fileSize, memStream.Length);
        }
      }
    }
        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"));
                }
            };
        }
Ejemplo n.º 15
0
 /*
  * Create gif for this test packa4
  * If there are more pics than the max (250), set the skip value slightly higher to skip extra images
  */
 public void createGif()
 {
     if (this.pngToGifFiles == null || this.pd == null) return;
     Console.WriteLine("[i] Creating gif for task " + this.taskIDNum);
     using (MagickImageCollection pngs = new MagickImageCollection())
     {
         int skip = 1, maxPics = 250, extraPics;
         if ((extraPics = pngToGifFiles.Length - maxPics) > 1) skip = (int)Math.Ceiling((double)pngToGifFiles.Length / maxPics);
         for (int i = 0, count = 0; i < pngToGifFiles.Length; i += skip)
         {
             pngs.Add(pngToGifFiles[i]);
             pngs[count++].AnimationDelay = 10;
         }
         pngs[0].AnimationIterations = 1;
         QuantizeSettings sett = new QuantizeSettings();
         sett.Colors = 256;
         pngs.Quantize(sett);
         pngs.Optimize();
         pngs.Write(this.pd + "install_" + this.taskIDNum + ".gif");
         foreach (string fileToDelete in this.pngToGifFiles) File.Delete(fileToDelete); // Delete the extra .png files
         Console.WriteLine("[\u221A] Gif created for task " + this.taskIDNum + ".");
     } // end pngs using
 }
Ejemplo n.º 16
0
		private static string GetDeviceStatePic(GKDevice device, GKState state)
		{
			var deviceConfig =
				GKManager.DeviceLibraryConfiguration.GKDevices.FirstOrDefault(d => d.DriverUID == device.DriverUID);
			if (deviceConfig == null)
			{
				return null;
			}
			var stateWithPic =
				deviceConfig.States.FirstOrDefault(s => s.StateClass == state.StateClass) ??
				deviceConfig.States.FirstOrDefault(s => s.StateClass == XStateClass.No);
			if (stateWithPic == null)
			{
				return null;
			}
			// Перебираем кадры в состоянии и генерируем gif картинку
			byte[] bytes;
			using (var collection = new MagickImageCollection())
			{
				foreach (var frame in stateWithPic.Frames)
				{
					var frame1 = frame;
					frame1.Image = frame1.Image.Replace("#000000", "#FF0F0F0F");
					Canvas surface;
					var imageBytes = Encoding.Unicode.GetBytes(frame1.Image ?? "");
					using (var stream = new MemoryStream(imageBytes))
					{
						surface = (Canvas)XamlServices.Load(stream);
					}
					var pngBitmap = surface != null ? InternalConverter.XamlCanvasToPngBitmap(surface) : null;
					if (pngBitmap == null)
					{
						continue;
					}
					var img = new MagickImage(pngBitmap)
					{
						AnimationDelay = frame.Duration / 10,
						HasAlpha = true
					};
					collection.Add(img);
				}
				if (collection.Count == 0)
				{
					return string.Empty;
				}
				//Optionally reduce colors
				QuantizeSettings settings = new QuantizeSettings { Colors = 256 };
				collection.Quantize(settings);

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

				using (var str = new MemoryStream())
				{
					collection.Write(str, MagickFormat.Gif);
					bytes = str.ToArray();
				}


			}
			return Convert.ToBase64String(bytes);
		}
Ejemplo n.º 17
0
        private void saveAsGifToolStripMenuItem_Click(object sender, EventArgs e)
        {
            String savedgif = null;
            saveFileDialog1.FileName = "animation.gif";
            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {

                savedgif = saveFileDialog1.FileName;

                String[] images = new String[arrayOfImages.Length];
                String log = "";
                int i = 0;
                String tmpDir = @"tmp\";
                if(Directory.Exists(@"tmp\")){

                } else {
                    Directory.CreateDirectory(@"tmp\");
                }
                using (ImageMagick.MagickImageCollection collection = new MagickImageCollection())
                {

                    foreach (PictureBox image in arrayOfImages)
                    {
                        Bitmap temp = (Bitmap)image.Image;
                        String name = tmpDir +"img" + i + ".png";
                       temp.Save(name);
                        images[i] = name;
                        i += 1;
                    }

                    foreach (String s in images)
                    {
                       collection.Add(s);
                       collection.Write(savedgif);
                        log += s;
                    }

                   // MessageBox.Show(log);

                    ImageWindow pos = new ImageWindow(wind, savedgif);
                }
            }
        }
Ejemplo n.º 18
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");
      }
    }
Ejemplo n.º 19
0
        private async void OnSelectedSourceFileChanged()
        {
            if (SelectedSourceFile == null ||
                !SelectedSourceFile.Exists)
                return;

            var settings = new MagickReadSettings
            {
                Density = new Density(150, 150),
                FrameIndex = 0,
                FrameCount = 1
            };

            var filename = Path.GetTempFileName();
            await Task.Run(() =>
            {
                try
                {
                    using (var images = new MagickImageCollection())
                    {
                        images.Read(SelectedSourceFile, settings);

                        var image = images.First();
                        image.Format = MagickFormat.Jpeg;
                        images.Write(filename);
                    }
                }
                catch (Exception ex)
                {
                    Log.Warn("Unable to preview document.", ex);
                    PreviewImage = null;
                    PreviewImageFilename = null;
                    SelectedFilePageCount = 0;
                }

                try
                {
                    using (var pdfReader = new PdfReader(SelectedSourceFile.FullName))
                        SelectedFilePageCount = pdfReader.NumberOfPages;
                }
                catch (Exception ex)
                {
                    Log.Warn("Unable to count pages.", ex);
                    SelectedFilePageCount = 0;
                }
            });

            try
            {
                var uri = new Uri(filename);
                var bitmap = new BitmapImage(uri);
                PreviewImage = bitmap;
                PreviewImageFilename = filename;
            }
            catch (Exception)
            {
                Log.Warn("Unable to preview selected document.");

                try
                {
                    var uri = new Uri("pack://application:,,,/PaperPusher;component/Art/unknown_icon_512.png");
                    var bitmap = new BitmapImage(uri);
                    PreviewImage = bitmap;
                }
                catch (Exception ex)
                {
                    Log.Error("Error showing unknown file icon.", ex);
                }
            }
        }