Esempio 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");
      }
    }
        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"));
                }
            };
        }
    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
      }
    }
 /*
  * 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
 }
Esempio n. 5
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);

            }
            
        }
 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]");
 }
Esempio n. 7
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();
            }
        }
Esempio n. 8
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);
		}