コード例 #1
0
        /// <summary>
        /// Iterator can be used for large GIF-files in order to display progress bar.
        /// </summary>
        public static Gif DecodeIteratorExample()
        {
            var bytes     = File.ReadAllBytes(Path);
            var parts     = Gif.DecodeIterator(bytes);
            var frames    = new List <GifFrame>();
            var stopwatch = new Stopwatch();
            var index     = 0;
            var time      = 0d;

            stopwatch.Start();

            foreach (var frame in parts)
            {
                frames.Add(frame);
                stopwatch.Stop();
                time += stopwatch.Elapsed.TotalSeconds;

                Console.WriteLine("GIF frame #{0} loaded in {1:n4}s", index++, stopwatch.Elapsed.TotalSeconds);

                stopwatch.Reset();
                stopwatch.Start();
            }

            Console.WriteLine("GIF loaded with iterator in {0:n4}s", time);

            return(new Gif(frames));
        }
コード例 #2
0
        private async Task GetTrendingStickers()
        {
            try
            {
                IsBusy = true;

                var retorno = await _api.GetTrendingStickerAsync("CYRh1lH68p3cMsrXqd6TYYU1YufBEwh3", 10);

                if (retorno.Meta.Status == (int)HttpStatusCode.OK)
                {
                    if (retorno.Data.Count > 0)
                    {
                        Gif = retorno;
                    }
                }
            }
            catch (Exception ex)
            {
                var msg = ex.Message;
                throw;
            }
            finally
            {
                IsBusy = false;
            }
        }
コード例 #3
0
        protected IList <Gif> UpdateResults(string query, string rating)
        {
            string       apiKey             = System.Web.Configuration.WebConfigurationManager.AppSettings["GiphyKey"];
            WebRequest   request            = WebRequest.Create("http://api.giphy.com/v1/gifs/search?q=" + query + "&limit=20&rating=" + rating + "api_key=" + apiKey); //Requests the data from the url
            WebResponse  response           = request.GetResponse();                                                                                                    //Gets everything back from that website into one object
            Stream       dataStream         = response.GetResponseStream();                                                                                             //Gets the response I want back, the json object
            StreamReader reader             = new StreamReader(dataStream);                                                                                             //Decodes the stream
            string       responseFromServer = reader.ReadToEnd();                                                                                                       //Saves it into a string

            //Convert from json to c#
            JObject parsedString = JObject.Parse(responseFromServer);

            IList <JToken> listedJsonObject = parsedString["data"].Children().Values("images").Values("fixed_width").ToList(); //Jumping into the {} of the json object, could do this several times to get data out of inner and upper layers

            IList <Gif> giphyResultsList = new List <Gif>();

            foreach (JToken result in listedJsonObject)
            {
                Gif found = result.ToObject <Gif>();
                giphyResultsList.Add(found);
            }

            //Close where necessary
            reader.Close();
            response.Close();

            return(giphyResultsList);
        }
コード例 #4
0
        public ActionResult Edit(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }

            Gif gif = _gifRepository.Get(id);

            if (gif == null)
            {
                return(HttpNotFound());
            }

            //Kod za proveru indetiteta
            if (gif.UserId != User.Identity.GetUserId())
            {
                return(HttpNotFound());
            }

            var viewModel = new GifEditViewModel()
            {
                Gif = gif
            };

            viewModel.Init(_categoryRepository);

            return(View(viewModel));
        }
コード例 #5
0
        public OrderQueue(Session session, OrderCacheItem queueInfo)
        {
            _queueInfo = queueInfo;
            InitializeComponent();
            imglist.Images.Add(UiUtility.Get24PxImageFrom16PxImg(Properties.Resources.user_16));
            Gif.SetLoadingImage(pbAnimate);

            Icon = Properties.Resources.icon_warning;
            InitSession(session);

            LoadInfo();

            _worker = new QueueOrderWorker(session)
            {
                TourFlag = _queueInfo.tourFlag
            };
            _worker.QueueMessageChanged    += _worker_QueueMessageChanged;
            _worker.QueryOrderQueueFailed  += _worker_QueryOrderQueueFailed;
            _worker.QueryOrderQueueSuccess += _worker_QueryOrderQueueSuccess;

            Load += (s, e) =>
            {
                btnClose.Enabled = false;
                _worker.RunQueryOrderQueue();
            };
            FormClosing += (s, e) =>
            {
                e.Cancel = _worker != null;
            };
            btnClose.DialogResult = DialogResult.Cancel;
            btnCancelQueue.Click += BtnCancelQueue_Click;
            FormPlacementManager.Instance.Control(this);
        }
コード例 #6
0
        private void clbTags_ItemCheck(object sender, ItemCheckEventArgs e)
        {
            //Get all selected in lstGifs
            if (lstFiles.SelectedItems.Count == 0)
            {
                return;
            }

            string     tagName = clbTags.Items[e.Index].ToString();
            List <Tag> tags    = GetTags();

            foreach (ListViewItem item in lstFiles.SelectedItems)
            {
                string fileName = Path.GetFileName(item.Text);
                Gif    gif      = gifDictionary[Path.GetFileName(fileName)];
                if (e.NewValue == CheckState.Unchecked)
                {
                    gif.GifTags.Remove(gif.GifTags.First(giftag => giftag.Tag.Name == tagName));
                }
                else if (e.NewValue == CheckState.Checked)
                {
                    if (gif.GifTags == null)
                    {
                        gif.GifTags = new List <GifTag>();
                    }
                    if (!gif.GifTags.Any(gifTag => gifTag.Tag.Name == tagName))
                    {
                        gif.GifTags.Add(new GifTag {
                            GifId = gif.Id, Tag = tags.First(tag => tag.Name == tagName)
                        });
                    }
                }
            }
        }
コード例 #7
0
        public static byte[] EncodeParallelExample(Gif gif)
        {
            var stopwatch = new Stopwatch();

            stopwatch.Start();

            var encodeProgress = new EncodeProgress();

            gif.EncodeParallel(progress =>
            {
                Console.WriteLine("Encode progress: {0}/{1}", progress.Progress, progress.FrameCount);
                encodeProgress = progress;
            });

            while (!encodeProgress.Completed)
            {
                Thread.Sleep(100);
            }

            if (encodeProgress.Exception != null)
            {
                throw encodeProgress.Exception;
            }

            stopwatch.Stop();

            Console.WriteLine("GIF encoded in {0:n2}s to binary.", stopwatch.Elapsed.TotalSeconds);

            return(encodeProgress.Bytes);
        }
コード例 #8
0
        public static void EncodeDecodeSaveTest()
        {
            var gif       = DecodeExample();
            var stopwatch = new Stopwatch();

            stopwatch.Start();

            var binary = gif.Encode();

            stopwatch.Stop();

            Console.WriteLine("GIF encoded in {0:n2}s to binary.", stopwatch.Elapsed.TotalSeconds);

            stopwatch.Reset();
            stopwatch.Start();

            Gif.Decode(binary);

            Console.WriteLine("GIF loaded from binary in {0:n2}s.", stopwatch.Elapsed.TotalSeconds);

            var path = Path.Replace(".gif", "_.gif");

            File.WriteAllBytes(path, binary);

            Console.WriteLine("GIF saved as {0}.", path);
            Console.WriteLine("Test passed!");
        }
コード例 #9
0
    public void StopRecording(int playerID)
    {
        return;



        if (playerID == 0)
        {
            recordedClip1 = Gif.StopRecording(recorder[playerID]);
            if (recordedClip1 == null)
            {
                return;
            }
        }
        else
        {
            recordedClip2 = Gif.StopRecording(recorder[playerID]);
            if (recordedClip2 == null)
            {
                return;
            }
        }



        //
        OpenPlaybackPanel(playerID);
    }
コード例 #10
0
        /// <summary>
        /// Iterator can be used for large GIF-files in order to display progress bar.
        /// </summary>
        public static byte[] EncodeIteratorExample(Gif gif)
        {
            var bytes        = new List <byte>();
            var parts        = gif.EncodeIterator();
            var iteratorSize = gif.GetEncodeIteratorSize();
            var stopwatch    = new Stopwatch();
            var index        = 0;
            var time         = 0d;

            stopwatch.Start();

            foreach (var part in parts)
            {
                if (index == iteratorSize - 1)                 // GIF header should be placed to sequence start!
                {
                    bytes.InsertRange(0, part);
                }
                else
                {
                    bytes.AddRange(part);
                }

                stopwatch.Stop();
                time += stopwatch.Elapsed.TotalSeconds;

                Console.WriteLine("GIF part #{0} encoded in {1:n4}s", index++, stopwatch.Elapsed.TotalSeconds);

                stopwatch.Reset();
                stopwatch.Start();
            }

            Console.WriteLine("GIF encoded with iterator in {0:n4}s", time);

            return(bytes.ToArray());
        }
コード例 #11
0
        public void Start()
        {
            var path = "Assets/GifAssets/PowerGif/Examples/Samples/Small.gif";

            if (path == "")
            {
                return;
            }

            var bytes = File.ReadAllBytes(path);

            _stopwatch.Reset();
            _stopwatch.Start();

            var gif = Gif.Decode(bytes);

            UnityEngine.Debug.LogFormat("Decoded in {0:N2}s", _stopwatch.Elapsed.TotalSeconds);

            _stopwatch.Reset();
            _stopwatch.Start();

            gif.Encode();

            UnityEngine.Debug.LogFormat("Encoded in {0:N2}s", _stopwatch.Elapsed.TotalSeconds);

            AnimatedImage.Play(gif);
        }
コード例 #12
0
        public override void OnEnter()
        {
            _player = playerType == PlayerType.ClipPlayer ? (IClipPlayer)clipPlayer : (IClipPlayer)clipPlayerUI;

            switch (actionType)
            {
            case ActionType.Play:
                var proxyClip = (AnimatedClipProxy)clip.Value;
                Gif.PlayClip(_player, proxyClip.clip, startDelay.Value, loop.Value);
                break;

            case ActionType.Pause:
                Gif.PausePlayer(_player);
                break;

            case ActionType.Resume:
                Gif.ResumePlayer(_player);
                break;

            case ActionType.Stop:
                Gif.StopPlayer(_player);
                break;
            }

            Finish();
        }
コード例 #13
0
 private void SaveGifs(List <string> filePaths)
 {
     if (filePaths.Count == 0)
     {
         return;
     }
     //Make this async and not on the main UI thread
     using (var gifContext = new GifContext()) {
         filePaths.ForEach(file => {
             try {
                 lstFiles.Items.RemoveByKey(file);
                 Gif gif = gifDictionary[Path.GetFileName(file)];
                 gifContext.Gifs.Add(gif);
                 foreach (var giftag in gif.GifTags)
                 {
                     gifContext.Entry(giftag.Tag).State = System.Data.Entity.EntityState.Unchanged;
                 }
                 File.Copy(file, Path.Combine(Gif.TargetDirectory, Path.GetFileName(file)));
             }
             catch (IOException ioException) {
             }
             catch (Exception exception) {
             }
         });
         gifContext.SaveChanges(); // Save changes to DB
     }
     MessageBox.Show("Saved " + filePaths.Count + " gifs");
     filePaths.Clear();
     gifDictionary.Clear();
 }
コード例 #14
0
        public ActionResult Index()
        {
            string apiKey = System.Web.Configuration.WebConfigurationManager.AppSettings["giphyAPIKey"];
            string query  = "funny cat";

            //Create the request to the API
            WebRequest request = WebRequest.Create("http://api.giphy.com/v1/gifs/search?q=" + query + "&api_key=" + apiKey);

            //Send that request off
            WebResponse respone = request.GetResponse();

            //Get back the response stram
            Stream stream = respone.GetResponseStream();

            //Make it accessible
            StreamReader reader = new StreamReader(stream);

            //Put into string , which is json formatted
            string resposneFromServer = reader.ReadToEnd();

            JObject parsedString = JObject.Parse(resposneFromServer);

            Gif myGifs = parsedString.ToObject <Gif>();

            return(View(myGifs));
        }
コード例 #15
0
        public async Task GifAsync([Summary("Gets Specific Gif By Identifier Number")] int num = -1)
        {
            var    watch   = new System.Diagnostics.Stopwatch();
            string comment = "";

            using (var gifContext = new GifContext()) {
                if (num == -1)
                {
                    //Get random gif
                    Random rand = new Random();
                    num     = rand.Next(0, gifContext.Gifs.Count());
                    comment = "random ";
                }

                Gif gif = gifContext.Gifs.First(g => g.Identifier == num);
                if (gif == null)
                {
                    await Context.Channel.SendMessageAsync("Gif Not Found");

                    return;
                }
                string fileName = gif.FileName;
                string fullPath = Gif.TargetDirectory + '\\' + fileName;
                gif.DisplayCount++;
                watch.Start();
                await gifContext.SaveChangesAsync();

                watch.Stop();
                await Context.Channel.SendFileAsync(fullPath, "Sending " + comment + "gif #" + num.ToString() + " took " + watch.ElapsedMilliseconds.ToString() + " ms to save");
            }
        }
コード例 #16
0
        public async Task Handle(Delete command)
        {
            Gif gif = _mapper.Map <Delete, Gif>(command);

            _db.Gifs.Remove(gif);
            await _db.SaveChangesAsync();
        }
コード例 #17
0
        public void AddAsEmoteG(Gif gif, IMessage m, string name = "uwu")
        {
            var guild     = Program.GetGuildFromChannel(m.Channel);
            var guildUser = guild.GetUser(m.Author.Id);

            if (!guildUser.GuildPermissions.AddReactions)
            {
                throw new Exception("U no have permission for dis :c");
            }

            using MemoryStream s = new MemoryStream();
            int maxWidth  = gif.Item1.Select(x => x.Width).Max();
            int maxHeight = gif.Item1.Select(x => x.Height).Max();

            using (AnimatedGifCreator c = new AnimatedGifCreator(s, -1))
                for (int i = 0; i < gif.Item1.Length; i++)
                {
                    c.AddFrame(gif.Item1[i].CropImage(new Rectangle(0, 0, maxWidth, maxHeight)), gif.Item2[i], GifQuality.Bit8);
                }

            guild.CreateEmoteAsync(name, new Discord.Image(s)).Wait();

            foreach (Bitmap b in gif.Item1)
            {
                b.Dispose();
            }
        }
コード例 #18
0
        public async Task Handle(Add command)
        {
            Gif gif = _mapper.Map <Add, Gif>(command);

            _db.Gifs.Add(gif);
            await _db.SaveChangesAsync();
        }
コード例 #19
0
        public ActionResult Index()
        {
            string apiKey = System.Web.Configuration.WebConfigurationManager.AppSettings["giphyAPIKey"];

            string query  = "funny dogs";
            Random random = new Random();
            string offset = random.Next(0, 400).ToString();

            //create the request to the API
            WebRequest request = WebRequest.Create("http://api.giphy.com/v1/gifs/search?q=" + query + "&api_key=" + apiKey + "&limit=30" + "&offset=" + offset);
            //send that API request
            WebResponse response = request.GetResponse();
            //Get back the response stream
            Stream stream = response.GetResponseStream();
            //make it accessible
            StreamReader reader = new StreamReader(stream);
            //put stream into string, which is JSON formatted
            string responseFromServer = reader.ReadToEnd();

            JObject parsedString = JObject.Parse(responseFromServer);

            Gif myGifs = parsedString.ToObject <Gif>();

            return(View(myGifs));
        }
コード例 #20
0
        public async Task <List <GifResult> > Search(string query)
        {
            var client = new TenorClient("5Z2X4KYG2HVW");

            Gif results = null;

            try{
                results = client.Search(query);
            }
            catch (Exception ex)
            {
                Debug.Write(ex.Message);
            }

            GifObject[] gifResult = null;

            if (results != null)
            {
                gifResult = results.GifResults;
            }

            return(gifResult.Select(x => new GifResult()
            {
                Width = x.Media[0][GifFormat.mp4].Dims[0],
                Height = x.Media[0][GifFormat.mp4].Dims[1],
                Tags = x.Tags.ToList(),
                Title = x.Title,
                Url = x.Media[0][GifFormat.mp4].Url.AbsoluteUri
            }).ToList());
        }
        /*
         * 12 Gif
         */
        public static Gif newGif(DControl ctl, StorageGif storageGif, Boolean isDesign)
        {
            string imgPath     = FileUtil.notExistsShowDefault(storageGif?.url, Params.GifNotExists);
            string imgFullPath = AppDomain.CurrentDomain.BaseDirectory + imgPath;

            DControlDto dto = DControlUtil.convert(ctl);

            dto.url = imgFullPath;
            Gif gif = new Gif(imgPath, isDesign);

            gif.HorizontalAlignment = HorizontalAlignment.Left;
            gif.VerticalAlignment   = VerticalAlignment.Top;
            gif.Margin     = new Thickness(ctl.left, ctl.top, 0, 0);
            gif.Width      = ctl.width;
            gif.Height     = ctl.height;
            gif.Background = Brushes.Transparent;

            gif.Opacity = ctl.opacity / 100.0;
            Panel.SetZIndex(gif, ctl.idx);
            gif.Focusable = false;
            gif.Tag       = dto;
            TransformGroup group = new TransformGroup();

            gif.RenderTransform       = group;
            gif.RenderTransformOrigin = new Point(0.5, 0.5);
            RotateTransform rotateTransform = TransformGroupUtil.GetRotateTransform(group);

            rotateTransform.Angle = ctl.rotateAngle;
            gif.Visibility        = Visibility.Visible;
            return(gif);
        }
コード例 #22
0
 public void StopRecording()
 {
     recordedClip = Gif.StopRecording(recorder);
     startRecordingButton.SetActive(true);
     stopRecordingButton.SetActive(false);
     recordingMark.SetActive(false);
 }
コード例 #23
0
        public void Start()
        {
            var bytes = File.ReadAllBytes(LargeSample);
            var gif   = Gif.Decode(bytes);

            AnimatedImage.Play(gif);
        }
コード例 #24
0
        public ActionResult Index()
        {
            string apiKey = System.Web.Configuration.WebConfigurationManager.AppSettings["GiphyAPIKey"];
            string query  = "pikachu";
            string offSet = "0";

            //Create the request to the API
            WebRequest request = WebRequest.Create("https://api.giphy.com/v1/gifs/search?api_key=" + apiKey + "&q=" + query + "&limit=25&offset=" + offSet + "&rating=G&lang=en");
            //Send the request off
            WebResponse response = request.GetResponse();
            //Get back the response stream
            Stream stream = response.GetResponseStream();
            //Make it accessible
            StreamReader reader = new StreamReader(stream);
            //Put into string which is json formatted
            string responseFromServer = reader.ReadToEnd();

            JObject parsedString = JObject.Parse(responseFromServer);

            Gif myGifs = parsedString.ToObject <Gif>();

            //Debug.WriteLine(myPokemon.moves[0].move.name);

            return(View(myGifs));
        }
コード例 #25
0
        public async Task Handle(Update command)
        {
            Gif gif = _mapper.Map <Update, Gif>(command);

            _db.Attach(gif);
            _db.Entry(gif).Property("Title").IsModified = true;
            await _db.SaveChangesAsync();
        }
コード例 #26
0
        public Gif FindGifByTitle(string Title)
        {
            Gif item = (from g in this.Gifs
                        where g.Title == Title
                        select g).FirstOrDefault();

            return(item);
        }
コード例 #27
0
        protected override Task OnOrderContextInitializeAsync()
        {
            Gif.SetLoadingImage(pbAnimate);
            ts.ApplyColorSchema(RowStyleType.Green);
            ts.Text = "正在初始化上下文...";

            return(base.OnOrderContextInitializeAsync());
        }
コード例 #28
0
        public Gif FindGifById(int ID)
        {
            Gif item = (from g in this.Gifs
                        where g.GifID == ID
                        select g).FirstOrDefault();

            return(item);
        }
コード例 #29
0
ファイル: GifService.cs プロジェクト: Vyacheslav-Kn/GiphyH
        public async Task <GifDTO> GetById(int id)
        {
            Gif gif = await _queryHandler.Find(new FindById {
                Id = id
            });

            return(_mapper.Map <Gif, GifDTO>(gif));
        }
コード例 #30
0
        private void btnBrowse_Click(object sender, EventArgs e)
        {
            OpenFileDialog fileDialog = new OpenFileDialog();

            fileDialog.Multiselect = true;
            fileDialog.Title       = "Select Gifs to Add";
            fileDialog.Filter      = "Gifs (*.GIF)|*.GIF|" + "All files (*.*)|*.*";
            DialogResult dr = fileDialog.ShowDialog();

            if (dr == DialogResult.OK)
            {
                using (var gifContext = new GifContext()) {
                    List <Gif> gifs = gifContext.Gifs.ToList <Gif>();

                    // Read the files
                    foreach (String file in fileDialog.FileNames)
                    {
                        // Create a PictureBox.
                        try {
                            if (!FilePaths.Contains(file))
                            {
                                if (!gifs.Any(gif => gif.FileName == Path.GetFileName(file)))
                                {
                                    Gif gif = new Gif {
                                        FileName = Path.GetFileName(file), CreatorId = User.ManagerId
                                    };
                                    lstFiles.Items.Add(file, file, 0);
                                    FilePaths.Add(file);
                                    gifDictionary[Path.GetFileName(file)] = gif;
                                }
                                else
                                {
                                    if (!DuplicateFilePaths.Contains(file))
                                    {
                                        DuplicateFilePaths.Add(file);
                                        lstDuplicate.Items.Add(file);
                                    }
                                }
                            }
                        }
                        catch (SecurityException ex) {
                            // The user lacks appropriate permissions to read files, discover paths, etc.
                            MessageBox.Show("Security error. Please contact your administrator for details.\n\n" +
                                            "Error message: " + ex.Message + "\n\n" +
                                            "Details (send to Support):\n\n" + ex.StackTrace
                                            );
                        }
                        catch (Exception ex) {
                            // Could not load the image - probably related to Windows file system permissions.
                            MessageBox.Show("Cannot add the image: " + file.Substring(file.LastIndexOf('\\'))
                                            + ". You may not have permission to read the file, or " +
                                            "it may be corrupt.\n\nReported error: " + ex.Message);
                        }
                    }
                }
            }
        }
コード例 #31
0
 public void Initialization(string OutputFile, int Width, int Height)
 {
     gif = new Gif();
     _outputFile = OutputFile;
 }