Class that contains setting for quantize operations.
示例#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");
      }
    }
示例#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));
 }
示例#3
0
 private QuantizeSettings CreateQuantizeSettings(XmlElement element)
 {
   if (element == null)
     return null;
   QuantizeSettings result = new QuantizeSettings();
   result.Colors = Variables.GetValue<Int32>(element, "colors");
   result.ColorSpace = Variables.GetValue<ColorSpace>(element, "colorSpace");
   result.DitherMethod = Variables.GetValue<Nullable<DitherMethod>>(element, "ditherMethod");
   result.MeasureErrors = Variables.GetValue<Boolean>(element, "measureErrors");
   result.TreeDepth = Variables.GetValue<Int32>(element, "treeDepth");
   return result;
 }
示例#4
0
 internal static INativeInstance CreateInstance(QuantizeSettings instance)
 {
   if (instance == null)
     return NativeInstance.Zero;
   return instance.CreateNativeInstance();
 }
    public void Test_Quantize()
    {
      using (MagickImageCollection collection = new MagickImageCollection())
      {
        ExceptionAssert.Throws<InvalidOperationException>(delegate ()
        {
          collection.Quantize();
        });

        collection.Add(Files.FujiFilmFinePixS1ProJPG);

        ExceptionAssert.Throws<ArgumentNullException>(delegate ()
        {
          collection.Quantize(null);
        });

        QuantizeSettings settings = new QuantizeSettings();
        settings.Colors = 3;

        MagickErrorInfo errorInfo = collection.Quantize(settings);
        Assert.IsNull(errorInfo);

#if Q8
        ColorAssert.AreEqual(new MagickColor("#2b414f"), collection[0], 66, 115);
        ColorAssert.AreEqual(new MagickColor("#7b929f"), collection[0], 179, 123);
        ColorAssert.AreEqual(new MagickColor("#44739f"), collection[0], 188, 135);
#elif Q16 || Q16HDRI
        ColorAssert.AreEqual(new MagickColor("#447073169f39"), collection[0], 66, 115);
        ColorAssert.AreEqual(new MagickColor("#7b4292c29f25"), collection[0], 179, 123);
        ColorAssert.AreEqual(new MagickColor("#2aef41654efc"), collection[0], 188, 135);
#else
#error Not implemented!
#endif
      }
    }
    public void Test_Map()
    {
      using (MagickImageCollection colors = new MagickImageCollection())
      {
        colors.Add(new MagickImage(MagickColors.Red, 1, 1));
        colors.Add(new MagickImage(MagickColors.Green, 1, 1));

        using (MagickImage remapImage = colors.AppendHorizontally())
        {
          using (MagickImageCollection collection = new MagickImageCollection())
          {
            ExceptionAssert.Throws<InvalidOperationException>(delegate ()
            {
              collection.Map(null);
            });

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

            collection.Read(Files.RoseSparkleGIF);

            ExceptionAssert.Throws<ArgumentNullException>(delegate ()
            {
              collection.Map(null);
            });

            QuantizeSettings settings = new QuantizeSettings();
            settings.DitherMethod = DitherMethod.FloydSteinberg;

            collection.Map(remapImage, settings);

            ColorAssert.AreEqual(MagickColors.Red, collection[0], 60, 17);
            ColorAssert.AreEqual(MagickColors.Green, collection[0], 37, 24);

            ColorAssert.AreEqual(MagickColors.Red, collection[1], 58, 30);
            ColorAssert.AreEqual(MagickColors.Green, collection[1], 36, 26);

            ColorAssert.AreEqual(MagickColors.Red, collection[2], 60, 40);
            ColorAssert.AreEqual(MagickColors.Green, collection[2], 17, 21);
          }
        }
      }
    }
 public void Quantize(MagickImage image, QuantizeSettings settings)
 {
   using (INativeInstance settingsNative = QuantizeSettings.CreateInstance(settings))
   {
     IntPtr exception = IntPtr.Zero;
     #if ANYCPU
     if (NativeLibrary.Is64Bit)
     #endif
     #if WIN64 || ANYCPU
     NativeMethods.X64.MagickImageCollection_Quantize(MagickImage.GetInstance(image), settingsNative.Instance, out exception);
     #endif
     #if ANYCPU
     else
     #endif
     #if !WIN64 || ANYCPU
     NativeMethods.X86.MagickImageCollection_Quantize(MagickImage.GetInstance(image), settingsNative.Instance, out exception);
     #endif
     CheckException(exception);
   }
 }
        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"));
                }
            };
        }
 /*
  * 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
 }
示例#10
0
        static void Main(string[] args)
        {
            string searchQuery = System.Windows.Forms.Clipboard.GetText();

            using (MagickImageCollection animation = new MagickImageCollection())  //Very few cartoons are broadcast live it's a terrible strain on the animators wrist.
            using (WebClient wc = new WebClient())                                  //The Internet, eh?
            {
                //Check the query
                List<a_lengthly_inefficient_search_at_the_taxpayers_expense>  searchResult
                    = JsonConvert.DeserializeObject<List<a_lengthly_inefficient_search_at_the_taxpayers_expense>>
                    (wc.DownloadString(Frinkiac.API_Root + "search?q=" + searchQuery.Replace(" ", "%20")));
                if (searchResult.Count <= resultIndex)      //Bad grammar overload.
                    throw new IndexOutOfRangeException("search string " + searchQuery + " not found");

                //Retrieve captions associated with result
                childrens_letters_to_god captionResult = JsonConvert.DeserializeObject<childrens_letters_to_god>(wc.DownloadString(Frinkiac.API_Root
                    + "caption?e=" + searchResult[resultIndex].Episode 
                    + "&t=" + searchResult[resultIndex].Timestamp));
                
                while (frameBatches > 0)
                {
                    foreach (an_arm_drawn_by_nobody_it_is_worth_nothing frame in captionResult.Neighboreenos)
                    {   //request each frame in captionQuery and add to our MagickImageCollection for the animation
                        MagickImage frameImage = new MagickImage(wc.DownloadData(Frinkiac.IMG_Root
                            + frame.Episode + "/"
                            + frame.Timestamp + ".jpg"), new MagickReadSettings());

                        frameImage.AnimationDelay = 20;

                        foreach (Anifrinkiac.you_egghead_writers_wouldve_never_thought_of_it caption in captionResult.Subtitles)       //Check out the subtitle results
                            if ((frame.Timestamp > caption.StartTimestamp)
                             && (frame.Timestamp < caption.EndTimestamp))
                                frameImage.Annotate(caption.Content, Gravity.South);    //Apply captions

                        animation.Add(frameImage);
                    }                     //Retrieve the next set of frames
                    if (frameBatches-- > 0)
                    {
                        captionResult = JsonConvert.DeserializeObject<childrens_letters_to_god>(wc.DownloadString(Frinkiac.API_Root
                    + "caption?e=" + searchResult[resultIndex].Episode
                    + "&t=" + captionResult.Neighboreenos[captionResult.Neighboreenos.Count - 1].Timestamp));
                        //Do it again for all new frames
                        captionResult = JsonConvert.DeserializeObject<childrens_letters_to_god>(wc.DownloadString(Frinkiac.API_Root
                            + "caption?e=" + searchResult[resultIndex].Episode
                            + "&t=" + captionResult.Neighboreenos[captionResult.Neighboreenos.Count - 1].Timestamp)); 
                    }
                }

                // Optionally reduce colors
                QuantizeSettings settings = new QuantizeSettings();
                settings.Colors = 256;
                animation.Quantize(settings);
                // Optionally optimize the images (images should have the same size).
                animation.Optimize();
                //Upload gif to imgur
                wc.Headers.Add("Authorization", "Client-ID " +  System.Configuration.ConfigurationManager.AppSettings["imgurClientID"].ToString());
                NameValueCollection values = new NameValueCollection
                    {
                        { "image", Convert.ToBase64String(animation.ToByteArray(MagickFormat.Gif)) }
                    };
                //Deserialize the xml reply
                XDocument reply = XDocument.Load(new MemoryStream(wc.UploadValues("https://api.imgur.com/3/upload.xml", values)));

                //Give up the goods
                System.Console.WriteLine(reply.Root.Element("link"));
                System.Windows.Forms.Clipboard.SetText(reply.Root.Element("link").Value + " : " + searchQuery);

            }
            
        }
示例#11
0
    public void Test_Quantize()
    {
      QuantizeSettings settings = new QuantizeSettings();
      settings.Colors = 8;

      Assert.AreEqual(DitherMethod.Riemersma, settings.DitherMethod);
      settings.DitherMethod = null;
      Assert.AreEqual(null, settings.DitherMethod);
      settings.DitherMethod = DitherMethod.No;
      Assert.AreEqual(DitherMethod.No, settings.DitherMethod);

      using (MagickImage image = new MagickImage(Files.FujiFilmFinePixS1ProJPG))
      {
        image.Quantize(settings);
      }
    }
示例#12
0
    public void Test_Quantize()
    {
      QuantizeSettings settings = new QuantizeSettings();
      settings.Colors = 8;

      Assert.AreEqual(DitherMethod.Riemersma, settings.DitherMethod);
      settings.DitherMethod = null;
      Assert.AreEqual(null, settings.DitherMethod);
      settings.DitherMethod = DitherMethod.No;
      Assert.AreEqual(DitherMethod.No, settings.DitherMethod);
      settings.MeasureErrors = true;
      Assert.AreEqual(true, settings.MeasureErrors);

      using (MagickImage image = new MagickImage(Files.FujiFilmFinePixS1ProJPG))
      {
        MagickErrorInfo errorInfo = image.Quantize(settings);
#if Q8
        Assert.AreEqual(6.975, errorInfo.MeanErrorPerPixel, 0.001);
#elif Q16 || Q16HDRI
        Assert.AreEqual(1803.2, errorInfo.MeanErrorPerPixel, 0.1);
#else
#error Not implemented!
#endif
        Assert.AreEqual(0.352, errorInfo.NormalizedMaximumError, 0.002);
        Assert.AreEqual(0.001, errorInfo.NormalizedMeanError, 0.001);
      }
    }
示例#13
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();
            }
        }
示例#14
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);
		}
示例#15
0
 public bool Map(MagickImage image, QuantizeSettings settings)
 {
   using (INativeInstance settingsNative = QuantizeSettings.CreateInstance(settings))
   {
     IntPtr exception = IntPtr.Zero;
     bool result;
     #if ANYCPU
     if (NativeLibrary.Is64Bit)
     #endif
     #if WIN64 || ANYCPU
     result = NativeMethods.X64.MagickImage_Map(Instance, MagickImage.GetInstance(image), settingsNative.Instance, out exception);
     #endif
     #if ANYCPU
     else
     #endif
     #if !WIN64 || ANYCPU
     result = NativeMethods.X86.MagickImage_Map(Instance, MagickImage.GetInstance(image), settingsNative.Instance, out exception);
     #endif
     CheckException(exception);
     return result;
   }
 }