예제 #1
0
파일: GitHelper.cs 프로젝트: qs93/photo
        /// <summary>
        /// 合併gif
        /// </summary>
        public static void GetThumbnail(string imgName, string type, Image addImg)
        {
            string re = ""; // 用于保存操作结果的变量

            try
            {
                string             outPutPath = HttpContext.Current.Server.MapPath(string.Format("~/timg/{0}.gif", imgName)); // 生成保存圖片的名稱
                AnimatedGifEncoder animate    = new AnimatedGifEncoder();
                animate.Start(outPutPath);
                animate.SetRepeat(0); // -1:不重複,0:循環
                List <Image> imgList  = GetFrames(HttpContext.Current.Server.MapPath(string.Format("~/timg/demo/{0}-words.gif", type)));
                var          imgCount = imgList.Count;
                animate.SetDelay(delay);  //設置時間
                for (int i = 0; i < imgCount; i++)
                {
                    if ((i + 1) == imgCount)
                    {
                        animate.SetDelay(3000);
                        animate.AddFrame(addImg);
                        //addImg.Save(HttpContext.Current.Server.MapPath("../timg/p" + i + ".jpg"));
                    }
                    else
                    {
                        animate.AddFrame(imgList[i]); // 添加帧
                                                      //imgList[i].Save(HttpContext.Current.Server.MapPath("../timg/p" + i + ".jpg"));
                    }
                }
                animate.Finish();
            }
            catch (Exception ex)
            {
                re = ex.Message;
            }
        }
예제 #2
0
        // TODO organise
        /// <summary>
        /// Encodes a compressed byte[] list containing image data as a gif to the desired location
        /// </summary>
        /// <param name="frames">Compressed byte array defining an image</param>
        /// <param name="delay">The delay between frames</param>
        /// <param name="quality">The quality of the gif</param>
        /// <param name="repeat">Repeat mode</param>
        /// <param name="location">Where the gif will be saved</param>
        /// <param name="percentageProgress">Interface used to determine the current task progress</param>
        /// <param name="fromIndex">From which index will the list of frames start to be encoded</param>
        /// <param name="toIndex">Until which index will the list of frames be encoded</param>
        /// <param name="frameIndexIncremet">Used to skip frames if <see cref="frameIndexIncremet"/> > 1</param>
        public static async Task EncodeGifBytes(
            List <byte[]> frames,
            int delay,
            int quality,
            int repeat,
            string location,
            IProgress <float> percentageProgress,
            int fromIndex          = 0,
            int toIndex            = -1,
            int frameIndexIncremet = 1)
        {
            if (toIndex < 0)
            {
                toIndex = frames.Count;
            }

            await Task.Run(() =>
            {
                var age = new AnimatedGifEncoder();
                age.Start(location);
                age.SetDelay(delay);
                age.SetQuality(quality);
                age.SetRepeat(repeat);
                for (int i = fromIndex; i < toIndex; i += frameIndexIncremet)
                {
                    if (percentageProgress != null)
                    {
                        percentageProgress.Report((float)(i - fromIndex) / (float)(toIndex - fromIndex));
                    }

                    age.AddFrame(BytesToImage(frames[i]));
                }
                age.Finish();
            });
        }
예제 #3
0
        /// <summary>
        /// 把directory文件夹里的png文件生成为gif文件,放在giffile
        /// </summary>
        /// <param name="directory">png文件夹</param>
        /// <param name="giffile">gif保存路径</param>
        /// <param name="time">每帧的时间/ms</param>
        /// <param name="repeat">是否重复</param>
        public static void PngsToGif(string directory, string giffile, int time, bool repeat)
        {
            //一般文件名按顺序排
            //string[] pngfiles = Directory.GetFileSystemEntries(directory, "*.png");
            string[]           pngfiles = Directory.GetFileSystemEntries(directory);
            AnimatedGifEncoder e        = new AnimatedGifEncoder();

            e.Start(giffile);

            //每帧播放时间
            //e.SetDelay(3000);

            //-1:不重复,0:重复
            e.SetRepeat(repeat ? 0 : -1);
            int inttime = 2000;

            for (int i = 0, count = pngfiles.Length; i < count; i++)
            {
                e.SetDelay(inttime);
                e.AddFrame(Image.FromFile(pngfiles[i]));

                inttime += 4000;
            }
            e.Finish();
        }
예제 #4
0
        static void Main(string[] args)
        {
            /* create Gif */
            //you should replace filepath
            //String [] imageFilePaths = new String[]{"c:\\01.png","c:\\02.png","c:\\03.png"};
            string[]           imageFilePaths = Directory.GetFiles(@"C:\Users\brush\Desktop\images");
            String             outputFilePath = "c:\\test.gif";
            AnimatedGifEncoder e   = new AnimatedGifEncoder();
            MemoryStream       mem = new MemoryStream();

            e.Start(mem);
            e.SetDelay(500);
            //-1:no repeat,0:always repeat
            e.SetRepeat(0);
            for (int i = 0, count = imageFilePaths.Length; i < count; i++)
            {
                e.AddFrame(Image.FromFile(imageFilePaths[i]));
            }
            e.Finish();

            File.WriteAllBytes("c:/users/brush/desktop/test.gif", mem.GetBuffer());

            /* extract Gif */
            GifDecoder gifDecoder = new GifDecoder();

            gifDecoder.Read("c:/users/brush/desktop/test.gif");
            for (int i = 0, count = gifDecoder.GetFrameCount(); i < count; i++)
            {
                Image frame = gifDecoder.GetFrame(i);                    // frame i
                frame.Save("c:/users/brush/desktop/" + Guid.NewGuid().ToString() + ".png", ImageFormat.Png);
            }
        }
예제 #5
0
        public byte[] GetWaitShot()
        {
            GifDecoder gifDecoder = new GifDecoder();

            AnimatedGifEncoder gifEncoder = new AnimatedGifEncoder();
            MemoryStream       outStream  = new MemoryStream();

            gifEncoder.SetFrameRate(10);
            gifEncoder.SetDelay(100);
            gifEncoder.SetRepeat(0);
            gifEncoder.SetTransparent(Color.Black);

            gifEncoder.Start(outStream);

            ResourceManager rm = new ResourceManager("webshot.serv.Properties.Resources", System.Reflection.Assembly.GetExecutingAssembly());

            gifDecoder.Read(rm.GetStream("ajax_loader"));

            for (int i = 0, count = gifDecoder.GetFrameCount(); i < count; i++)
            {
                gifEncoder.AddFrame(gifDecoder.GetFrame(i), thumbwidth, thumbheight);
            }

            gifEncoder.Finish();

            byte[] buffer = outStream.ToArray();

            outStream.Close();

            return(buffer);
        }
예제 #6
0
        /// <summary>
        ///
        /// </summary>
        private void Process()
        {
            GenerateIdentifyingCode(_defaultIdentifyingCodeLen);

            Brush     br   = Brushes.White;
            Rectangle rect = new Rectangle(0, 0, Width, Height);
            Font      f    = new Font(FontFamily.GenericSansSerif, 14, FontStyle.Bold);

            for (int i = 0; i < _frameCount; i++)
            {
                Image    im = new Bitmap(Width, Height);
                Graphics ga = Graphics.FromImage(im);

                ga.FillRectangle(br, rect);

                int fH = (int)f.GetHeight();
                int fW = (int)ga.MeasureString(IdentifyingCode, f).Width;

                AddNoise(ga);

                ga.DrawString(IdentifyingCode, f, SystemBrushes.Desktop, new PointF(random.Next(1, Width - 1 - fW), random.Next(1, Height - 1 - fH)));
                ga.Flush();
                coder.SetDelay(_delay);
                coder.AddFrame(im);
                im.Dispose();
            }
            coder.Finish();
        }
예제 #7
0
파일: Form1.cs 프로젝트: icprog/PC
        private void convertToGifToolStripMenuItem_Click(object sender, EventArgs e)
        {
            String outputPath = "C:\\" + number.ToString() + ".gif";

            if (File.Exists(outputPath))
            {
                imageBox.Image = null;
                number++;
                outputPath = "C:\\" + number.ToString() + ".gif";
            }
            AnimatedGifEncoder gif = new AnimatedGifEncoder();

            gif.Start(outputPath);
            gif.SetDelay(trackBar1.Value);
            gif.SetRepeat(0);
            for (int i = 0; i < count; i++)
            {
                gif.AddFrame(srcImage.ElementAt(i));
            }
            gif.Finish();
            imageBox.Image  = (Image)Image.FromFile(outputPath);
            imageBox.Width  = srcImage.ElementAt(0).Width;
            imageBox.Height = srcImage.ElementAt(0).Height;
            MessageBox.Show("Done!");
        }
예제 #8
0
        static void Main(string[] args)
        {
            /* create Gif */
            //you should replace filepath
//			String [] imageFilePaths = new String[]{"D:\\0.bmp","D:\\2.bmp","D:\\3.bmp","D:\\4.bmp","D:\\5.bmp","D:\\6.bmp","D:\\7.bmp","D:\\8.bmp","D:\\9.bmp","D:\\10.bmp","D:\\11.bmp","D:\\12.bmp","D:\\13.bmp","D:\\14.bmp","D:\\15.bmp","D:\\16.bmp","D:\\17.bmp","D:\\18.bmp","D:\\19.bmp","D:\\20.bmp","D:\\21.bmp","D:\\22.bmp","D:\\23.bmp","D:\\24.bmp","D:\\25.bmp","D:\\26.bmp","D:\\27.bmp","D:\\28.bmp","D:\\29.bmp","D:\\30.bmp","D:\\31.bmp","D:\\32.bmp","D:\\33.bmp","D:\\34.bmp","D:\\35.bmp","D:\\36.bmp","D:\\37.bmp","D:\\38.bmp"};
            String[]           imageFilePaths = new String[] { "D:\\0.bmp", "D:\\1.bmp", "D:\\2.bmp", "D:\\3.bmp", "D:\\4.bmp", "D:\\5.bmp" };
            String             outputFilePath = "D:\\test.gif";
            AnimatedGifEncoder e = new AnimatedGifEncoder();

            e.Start(outputFilePath);
            e.SetDelay(200);
            //-1:no repeat,0:always repeat
            e.SetRepeat(0);
            for (int i = 0, count = imageFilePaths.Length; i < count; i++)
            {
                e.AddFrame(Image.FromFile(imageFilePaths[i]));
            }
            e.Finish();
            /* extract Gif */
            string     outputPath = "D:\\";
            GifDecoder gifDecoder = new GifDecoder();

            gifDecoder.Read("C:\\test.gif");
            for (int i = 0, count = gifDecoder.GetFrameCount(); i < count; i++)
            {
                Image frame = gifDecoder.GetFrame(i);                    // frame i
                frame.Save(outputPath + Guid.NewGuid().ToString() + ".png", ImageFormat.Png);
            }
        }
예제 #9
0
        private void GenerateGif(object sender, DoWorkEventArgs e)
        {
            GifArgument        argument = e.Argument as GifArgument;
            AnimatedGifEncoder encoder  = new AnimatedGifEncoder();

            encoder.Start(argument.outputFilePath);
            encoder.SetDelay(argument.frameRate);
            encoder.SetRepeat(0);
            // generate gif
            for (int i = 0; i < argument.fileList.Count; i++)
            {
                if (worker.CancellationPending)
                {
                    e.Cancel = true;
                    return;
                }
                encoder.AddFrame(System.Drawing.Image.FromFile(argument.fileList[i]));
                if (i == argument.fileList.Count - 1)
                {
                    worker.ReportProgress(100);
                }
                else
                {
                    worker.ReportProgress((int)(100.0 * i / argument.fileList.Count));
                }
            }
            e.Result = argument.outputFilePath;
        }
예제 #10
0
        /// <summary>
        /// 将图片集合转换为GIF
        /// </summary>
        /// <param name="imgFilePaths">图片集合路径</param>
        /// <param name="gifFileName">输出gif文件路径</param>
        /// <param name="Delay">每帧间隔毫秒</param>
        /// <returns></returns>
        public static bool ImageToGif(string[] imgFilePaths, string gifFileName, int Delay)
        {
            try
            {
                //String[] imageFilePaths = new String[] { "c:\\01.png", "c:\\02.png", "c:\\03.png" };
                //String outputFilePath = "c:\\test.gif";
                AnimatedGifEncoder e = new AnimatedGifEncoder();
                e.Start(gifFileName);
                e.SetDelay(Delay);
                //-1:no repeat,0:always repeat
                e.SetRepeat(0);
                for (int i = 0, count = imgFilePaths.Length; i < count; i++)
                {
                    var img = Image.FromFile(imgFilePaths[i]);
                    e.AddFrame(img);
                    img.Dispose();
                }
                e.Finish();

                return(true);
            }
            catch
            {
                return(false);
            }
        }
예제 #11
0
        public void Create_Png_Img_To_Gif_Test()
        {
            foreach (var imgFilePath in imageFilePaths)
            {
                if (!File.Exists(imgFilePath))
                {
                    Assert.IsFalse(false, "文件路径不存在");
                }
            }
            if (File.Exists(outputImagePath))
            {
                File.Delete(outputImagePath);
            }
            AnimatedGifEncoder e1 = new AnimatedGifEncoder();

            e1.Start(outputImagePath);
            //e1.Delay = 500;    // 延迟间隔
            e1.SetDelay(500);
            e1.SetRepeat(0);  //-1:不循环,0:总是循环 播放
            e1.SetSize(100, 200);
            foreach (var imgFilePath in imageFilePaths)
            {
                e1.AddFrame(System.DrawingCore.Image.FromFile(imgFilePath));
            }
            e1.Finish();
            var isExists = File.Exists(outputImagePath);

            Assert.IsTrue(isExists, "文件存在,生成成功");
        }
예제 #12
0
        static void Main(string[] args)
        {
            /* create Gif */
            //you should replace filepath
            String []          imageFilePaths = new String[] { "c:\\01.png", "c:\\02.png", "c:\\03.png" };
            String             outputFilePath = "c:\\test.gif";
            AnimatedGifEncoder e = new AnimatedGifEncoder();

            // read file as memorystream
            byte[]       fileBytes = File.ReadAllBytes(outputFilePath);
            MemoryStream memStream = new MemoryStream(fileBytes);

            e.Start(memStream);
            e.SetDelay(500);
            //-1:no repeat,0:always repeat
            e.SetRepeat(0);
            for (int i = 0, count = imageFilePaths.Length; i < count; i++)
            {
                e.AddFrame(Image.FromFile(imageFilePaths[i]));
            }
            e.Finish();
            /* extract Gif */
            string     outputPath = "c:\\";
            GifDecoder gifDecoder = new GifDecoder();

            gifDecoder.Read("c:\\test.gif");
            for (int i = 0, count = gifDecoder.GetFrameCount(); i < count; i++)
            {
                Image frame = gifDecoder.GetFrame(i);                    // frame i
                frame.Save(outputPath + Guid.NewGuid().ToString() + ".png", ImageFormat.Png);
            }
        }
예제 #13
0
        /// <summary>
        /// Initializes a new instance of the <see cref="GifVertify"/> class.
        /// </summary>
        /// <param name="request">The request.</param>
        public GifVertify(HttpRequestBase request)
        {
            string currentPath = request.PhysicalApplicationPath;

            string[] mFrames = new string[] { currentPath + @"Images\other\1.jpg", currentPath + @"Images\other\3.jpg", currentPath + @"Images\other\2.jpg" };

            string verPath = currentPath + @"Images\index\ver.gif";

            FileInfo file = new FileInfo(verPath);

            if (file.Exists)
            {
                file.Delete();
            }

            AnimatedGifEncoder mEncoder = new AnimatedGifEncoder();

            mEncoder.Start(verPath);
            mEncoder.SetDelay(300);
            mEncoder.SetRepeat(0);

            for (int i = 0; i < mFrames.Length; i++)
            {
                mEncoder.AddFrame(Image.FromFile(mFrames[i]));
            }

            mEncoder.Finish();
            _result = mFrames.Length.ToString();
        }
예제 #14
0
        private void pictureBox9_Click(object sender, EventArgs e)
        {
            /* create Gif */
            //you should replace filepath
            /*String[] imageFilePaths = new String[] { @"C:\Users\Administrator\Desktop\imagini\resurse\1.jpg", @"C:\Users\Administrator\Desktop\imagini\resurse\2.jpg", @"C:\Users\Administrator\Desktop\imagini\resurse\3.jpg", @"C:\Users\Administrator\Desktop\imagini\resurse\4.jpg", @"C:\Users\Administrator\Desktop\imagini\resurse\5.jpg" };*/
            /*String outputFilePath = @"C:\Users\Administrator\Desktop\imagini\resurse\test.gif";*/
            sfd.Filter = "GIF|*.GIF|All files (*.*)|*.*";
            if (sfd.ShowDialog() == DialogResult.OK)
            {
                tmp = Convert.ToInt32(textBox1.Text);
                String             outputFilePath = sfd.FileName;
                AnimatedGifEncoder s = new AnimatedGifEncoder();
                s.Start(outputFilePath);
                tmp = tmp;
                s.SetDelay(tmp);
                //-1:no repeat,0:always repeat
                s.SetRepeat(0);

                /*for (int i = 0, count = imageFilePaths.Length; i < count; i++)
                 * {
                 *  s.AddFrame(Image.FromFile(imageFilePaths[i]));
                 * }*/
                for (int i = 0, count = img.Length; i < count; i++)
                {
                    s.AddFrame(img[i]);
                }
                /* extract Gif */
                s.Finish();
                MessageBox.Show("GIF-ul a fost creat cu succes!");
                //Application.Exit();
            }
        }
예제 #15
0
        private void button1_Click(object sender, EventArgs e)
        {
            if (listView1.Items.Count < 1)
            {
                MessageBox.Show("Drop source files first!", this.Text);
                return;
            }
            if ((file1.Text == "") && !ChooseFile())
            {
                return;
            }

            picture1.ImageLocation = "";

            Cursor.Current = Cursors.WaitCursor;

            String             outputFilePath = file1.Text;
            AnimatedGifEncoder enc            = new AnimatedGifEncoder();

            enc.Start(outputFilePath);
            enc.SetDelay((int)delay1.Value);
            //-1:no repeat,0:always repeat
            enc.SetRepeat(loop1.Checked ? 0 : -1);
            //for (int i = 0, count = imageFilePaths.Length; i < count; i++)
            foreach (ListViewItem i in listView1.Items)
            {
                enc.AddFrame(Image.FromFile(i.Text));
            }
            enc.Finish();

            picture1.ImageLocation = outputFilePath;

            Cursor.Current = Cursors.Default;
        }
예제 #16
0
        public override byte[] CreateImage(out string validataCode)
        {
            Bitmap bitmap;
            string formatString = "a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z";

            GetRandom(formatString, this.ValidataCodeLength, out validataCode);
            MemoryStream       stream  = new MemoryStream();
            AnimatedGifEncoder encoder = new AnimatedGifEncoder();

            encoder.Start();
            encoder.SetDelay(1);
            encoder.SetRepeat(0);
            for (int i = 0; i < 3; i++)
            {
                this.SplitCode(validataCode);
                this.ImageBmp(out bitmap, validataCode);
                bitmap.Save(stream, ImageFormat.Png);
                encoder.AddFrame(Image.FromStream(stream));
                stream = new MemoryStream();
                bitmap.Dispose();
            }
            encoder.OutPut(ref stream);
            bitmap = null;
            stream.Close();
            stream.Dispose();
            return(stream.GetBuffer());
        }
예제 #17
0
        private void button_run_Click(object sender, EventArgs e0)
        {
            button_run.Enabled = false;
            var start = DateTime.Now;

            var pngfiles = this.fileOpenControl_input.FilePathes;
            var giffile  = this.fileOutputControl_outGif.FilePath;

            bool isRepeat = this.checkBox_repeat.Checked;
            var  interval = namedIntControl_delayMs.Value;

            AnimatedGifEncoder e = new AnimatedGifEncoder();

            e.Start(giffile);

            //每帧播放时间
            e.SetDelay(interval);

            //-1:不重复,0:重复
            e.SetRepeat(isRepeat ? 0 : -1);
            foreach (var path in pngfiles)
            {
                e.AddFrame(Image.FromFile(path));
            }

            e.Finish();
            var span = DateTime.Now - start;

            log.Info("处理完毕,耗时 :" + span.TotalSeconds.ToString("0.00") + " 秒 = " + span.ToString());

            Geo.Utils.FormUtil.ShowOkAndOpenDirectory(giffile);

            button_run.Enabled = true;
        }
예제 #18
0
        /// <summary>
        /// Ulozi obrazek ve formatu GIF
        /// </summary>
        /// <param name="filename"></param>
        /// <param name="delay"></param>
        /// <param name="repeat"></param>
        public void SaveToGif(string path, short delay, bool repeat)
        {
            AnimatedGifEncoder aniEncoder = new AnimatedGifEncoder();

            aniEncoder.Start(path);
            aniEncoder.SetDelay(delay);
            aniEncoder.SetRepeat(repeat ? 0 : -1);

            using (MemoryStream memoryStream = new MemoryStream())
            {
                int lastIndex = morphManager.KeyFrames[morphManager.KeyFrames.Count - 1].Index;
                for (int i = 0; i <= lastIndex; i++)
                {
                    Morphing.Core.Frame frame = morphManager.GetFrame(i);
                    if (frame.WarpedBitmap == null)
                    {
                        continue;
                    }

                    // Vytvoreni gif obrazku a vlozeni do kolekce snimku
                    GifBitmapEncoder gifEncoder = new GifBitmapEncoder();
                    gifEncoder.Frames.Add(BitmapFrame.Create(frame.WarpedBitmap));
                    gifEncoder.Save(memoryStream);
                    aniEncoder.AddFrame(System.Drawing.Image.FromStream(memoryStream));
                    memoryStream.Seek(0, SeekOrigin.Begin);
                }
                aniEncoder.Finish();
            }
            selectedFrame.ApplyWarping();
        }
예제 #19
0
        //Step 1:引用Gif.Components.dll
        //Step 2:准备所有需要的图片,这里用directory表示
        //Step 3:生成gif,路径为 file
        //nyc 2018年2月2日15:52:04
        public static string  CGif()
        {
            string directory = @"F:\1";
            bool   repeat    = true;

            //一般文件名按顺序排
            string[] pngfiles = Directory.GetFileSystemEntries(directory, "*.png");

            AnimatedGifEncoder e      = new AnimatedGifEncoder();
            string             Folder = System.Web.HttpContext.Current.Server.MapPath("~/upload/combine/");

            if (!Directory.Exists(Folder))
            {
                Directory.CreateDirectory(Folder);
            }
            var data = DateTime.Now.ToString("yyyyMMddHHmmss");
            var file = System.Web.HttpContext.Current.Server.MapPath("~/upload/combine/") + data + ".gif";

            e.Start(file);

            //每帧播放时间
            e.SetDelay(500);

            //-1:不重复,0:重复
            e.SetRepeat(repeat ? 0 : -1);
            for (int i = 0, count = pngfiles.Length; i < count; i++)
            {
                e.AddFrame(System.Drawing.Image.FromFile(pngfiles[i]));
            }
            e.Finish();
            return(file);
        }
예제 #20
0
        public bool SaveAsGif(string path)
        {
            Error = "";
            AnimatedGifEncoder encoder = new AnimatedGifEncoder();

            if (!encoder.Start(path))
            {
                Error = "Failed to start the GIF encoder :(";
                return(false);
            }

            encoder.SetTransparent(Color.Black);
            encoder.SetDelay(100);
            encoder.SetRepeat(0); // -1:no repeat, 0:always repeat

            foreach (Bitmap bmp in Frames)
            {
                if (!encoder.AddFrame(bmp))
                {
                    Error = "Failed to add frame to GIF encoder :(";
                    return(false);
                }
            }

            if (!encoder.Finish())
            {
                Error = "GIF encoder failed to finish :(";
                return(false);
            }

            return(true);
        }
예제 #21
0
        public static bool CompressGif(List <string> gifPath, string outputPath, int ms, int repeat)
        {
            try
            {
                AnimatedGifEncoder gif = new AnimatedGifEncoder();

                gif.Start(outputPath);
                gif.SetDelay(ms);

                //-1:no repeat,0:always repeat
                gif.SetRepeat(repeat);

                for (int i = 0, count = gifPath.Count; i < count; i++)
                {
                    using (Image img = Image.FromFile(gifPath.ElementAt(i)))
                        gif.AddFrame(img);
                }

                gif.Finish();

                return(true);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return(false);
            }
        }
예제 #22
0
        /// <summary>
        /// 多张图片转成一张gif图片
        /// </summary>
        /// <param name="imageFilePaths">图片路径,放到一个数组里面</param>
        /// <param name="gifPath">生成的gif图片路径</param>
        /// <param name="time">每一帧图片间隔时间</param>
        /// <param name="w">生成的gif图片宽度</param>
        /// <param name="h">生成的gif图片高度</param>
        /// <returns></returns>
        public static bool ConvertJpgToGif(List <System.Drawing.Image> images, string gifPath, int time, int w, int h)
        {
            try
            {
                AnimatedGifEncoder e = new AnimatedGifEncoder();
                e.Start(gifPath);
                e.SetDelay(time);
                //0:循环播放    -1:不循环播放
                e.SetRepeat(0);
                for (int i = 0, count = images.Count; i < count; i++)
                {
                    //e.AddFrame(Image.FromFile(Server.MapPath(imageFilePaths[i])));

                    System.Drawing.Image img = images[i];
                    //如果多张图片的高度和宽度都不一样,可以打开这个注释
                    img = ReSetPicSize(img, w, h);
                    e.AddFrame(img);
                }
                e.Finish();

                return(true);
            }
            catch (Exception ex)
            {
                return(false);
            }
        }
예제 #23
0
        static void Main(string[] args)
        {
            /* create Gif */
            //you should replace filepath
            String [] imageFilePaths = new String[] { @"F:\Mohamed ELhoseiny\Dropbox\Public\MMExperiment\08. Joh Adams\JohAdams2AllAll.jpg",
                                                      @"F:\Mohamed ELhoseiny\Dropbox\Public\MMExperiment\08. Joh Adams\JohAdams2AllClipArt.jpg",
                                                      @"F:\Mohamed ELhoseiny\Dropbox\Public\MMExperiment\08. Joh Adams\JohAdams2AllLineArt.jpg" };
            String             outputFilePath = "c:\\test.gif";
            AnimatedGifEncoder e = new AnimatedGifEncoder();

            e.Start(outputFilePath);
            e.SetDelay(4000);
            //-1:no repeat,0:always repeat
            e.SetRepeat(0);
            for (int i = 0, count = imageFilePaths.Length; i < count; i++)
            {
                e.AddFrame(Image.FromFile(imageFilePaths[i]));
            }
            e.Finish();
            /* extract Gif */
            string outputPath = "c:\\";
            //GifDecoder gifDecoder = new GifDecoder();
            //gifDecoder.Read( "c:\\test.gif" );
            //for ( int i = 0, count = gifDecoder.GetFrameCount(); i < count; i++ )
            //{
            //    Image frame = gifDecoder.GetFrame( i );  // frame i
            //    frame.Save( outputPath + Guid.NewGuid().ToString() + ".png", ImageFormat.Png );
            //}
        }
예제 #24
0
        private void AddImageToAnimation(DateTime timeStamp)
        {
            TimeSpan timeSpan = timeStamp.Subtract(_previousTimestamp);

            _AnimatedGifEncoder.SetDelay(timeSpan.Milliseconds);
            this._AnimatedGifEncoder.AddFrame(_previousImage);
            _previousImage = null;
        }
예제 #25
0
        private void GenerateGif(string tempFolder, string gifPath)
        {
            successful = false;
            if (!Directory.Exists(gifPath))
            {
                Directory.CreateDirectory(gifPath);
            }

            string _GifFileName = "gf_" + DateTime.Now.Ticks.ToString() + ".gif";

            gifPath = Path.Combine(gifPath, _GifFileName);
            gPath   = gifPath;
            try
            {
                var _fileExtension = System.IO.Path.GetExtension(ShortPathGIF);
                var files          = Directory.GetFiles(tempFolder, "*" + _fileExtension);

                AnimatedGifEncoder e = new AnimatedGifEncoder();
                e.Start(gifPath);
                e.SetQuality(100);
                e.SetDelay(framedelaytimer);
                e.SetSize((int)ExportWidth, (int)ExportHeight);
                //e.SetFrameRate(15);

                //-1:no repeat,0:always repeat
                e.SetRepeat(0);

                if (RotationCheck)
                {
                    e.AddFrame(Image.FromFile(files[0]));
                    for (int i = files.Length - 1, count = -1; i > count; i--)
                    {
                        e.AddFrame(Image.FromFile(files[i]));
                    }
                }
                else
                {
                    for (int i = 0, count = files.Length; i < count; i++)
                    {
                        e.AddFrame(Image.FromFile(files[i]));
                    }
                    e.AddFrame(Image.FromFile(files[0]));
                }

                e.Finish();
                GC.Collect();
                successful = true;
            }
            catch (Exception ex)
            {
                Log.Debug("", ex);
            }

            //if (successful == true)
            //{
            //    MessageBox.Show("Saved Successfully at location.." + Environment.NewLine + gifPath, "ExportGIF", MessageBoxButton.OK, MessageBoxImage.Information);
            //}
        }
예제 #26
0
        private void SaveImg(Processor prcsr, Saver sr, bool colored)
        {
            if (prcsr.res != null)
            {
                if (gif)
                {
                    //Console.WriteLine("Animating...");

                    AnimatedGifEncoder e = new AnimatedGifEncoder();

                    e.SetQuality(20);

                    string fname = "out_anim" + (colored ? "_colored" : "_bw") + ".gif";

                    if (File.Exists(fname))
                    {
                        File.Delete(fname);
                    }

                    e.Start(fname);
                    e.SetDelay(gif_speed);
                    e.SetRepeat(0);
                    int s = GIF_Frames.GetLength(0);

                    ProgressBar pb = new ProgressBar(s, 20);

                    pb.start();

                    DateTime dt = new DateTime();
                    dt = DateTime.Now;
                    for (int i = 0; i < s; i++)
                    {
                        pb.Progress(i);

                        Console.SetCursorPosition(pb.size + 2, pb.y);

                        Bitmap b = new Bitmap(sr.Save(GIF_Frames[i], colored));

                        b = new Bitmap(b, b.Width / 2, b.Height / 2);
                        e.AddFrame(b);
                        b.Dispose();
                    }

                    pb.End();
                    Console.WriteLine("Total time taken: " + (DateTime.Now - dt));

                    e.Finish();

                    e.SetDispose(-1);
                }
                else
                {
                    sr.Save(prcsr.res, colored).Save("out_ASCII" + (colored?"_colored":"_bw") + ".png");
                }
            }
        }
예제 #27
0
        private static void CreateGif(object stateInfo)
        {
            (string, ProgressBar, CountdownEvent)data = ((string, ProgressBar, CountdownEvent))stateInfo;
            string path = data.Item1;

            if (!File.Exists(path))
            {
                return;
            }

            using (ZipArchive archive = ZipFile.OpenRead(path))
            {
                using (ChildProgressBar pbar = data.Item2.Spawn(archive.Entries.Count, "Waiting: " + Path.GetFileName(path), childOptions))
                {
                    int delay = Program.delay;

                    ZipArchiveEntry jsonFile = archive.GetEntry("animation.json");
                    if (jsonFile != null && !Program.ignore)
                    {
                        JsonEntry[] frames = JsonSerializer.Deserialize <JsonEntry[]>(new StreamReader(jsonFile.Open()).ReadToEnd());
                        delay = frames[0].delay;
                    }

                    if (archive.Entries.Count == 0)
                    {
                        return;
                    }

                    AnimatedGifEncoder gif = new AnimatedGifEncoder();

                    gif.SetRepeat(0);
                    gif.SetDelay(delay);
                    using (MemoryStream memStream = new MemoryStream())
                    {
                        gif.Start(memStream);
                        foreach (ZipArchiveEntry entry in archive.Entries)
                        {
                            pbar.Tick($"{entry.Name}: {Path.GetFileName(path)}");
                            if (entry.FullName.EndsWith(".jpg", StringComparison.OrdinalIgnoreCase))
                            {
                                Image i = Image.FromStream(entry.Open());
                                gif.AddFrame(i);
                            }
                            pbar.Message = "Finished";
                        }
                        gif.Finish();
                        string outFile = keep?path.Remove(0, output.Length):Path.GetFileName(path);
                        outFile = output + outFile.Remove(outFile.Length - 3) + "gif";
                        Directory.CreateDirectory(Path.GetDirectoryName(outFile));
                        File.WriteAllBytes(outFile, memStream.ToArray());
                    }
                }
                data.Item2.Tick($"{data.Item2.MaxTicks - data.Item3?.CurrentCount - 1} out of {data.Item2.MaxTicks - 1}");
                data.Item3?.Signal();
            }
        }
예제 #28
0
        private string pic2meme(string image)
        {
            Notice.Content = "转换中...";

            var tmpImage = GenerateTempFile(".gif");

            if (convertMode == ConvertMode.QuickConvert)
            {
                try
                {
                    File.Copy(image, tmpImage);
                }
                catch
                {
                    tmpImage = null;
                }
            }
            else
            {
                try
                {
                    AnimatedGifEncoder e = new AnimatedGifEncoder();
                    e.Start(tmpImage);
                    //e.SetQuality(10);
                    e.SetDelay(1000);
                    e.SetRepeat(-1);
                    if (File.Exists(image))
                    {
                        e.AddFrame(Image.FromFile(image));
                    }
                    else
                    {
                        tmpImage = null;
                    }
                    e.Finish();
                }
                catch
                {
                    tmpImage = null;
                }
            }

            if (!string.IsNullOrEmpty(tmpImage))
            {
                Notice.Content = "转换成功,直接粘贴到微信发送即可";
                SetImageToClipboard(tmpImage);
                SetPreview(tmpImage);
            }
            else
            {
                Notice.Content = "转换失败";
            }

            return(tmpImage);
        }
예제 #29
0
        public override byte[] CreateImage(out string validataCode)
        {
            string strFormat = "a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z";

            GetRandom(strFormat, this.ValidataCodeLength, out validataCode);

            Bitmap       bitmap;
            MemoryStream stream = new MemoryStream();

            AnimatedGifEncoder encoder = new AnimatedGifEncoder();

            encoder.Start();
            encoder.SetDelay(1);
            encoder.SetRepeat(0);

            Random rand = new Random();

            for (int i = 0; i < validataCode.Length; i++)
            {
                colors.Add(DrawColors[rand.Next(DrawColors.Length)]);
            }

            for (int i = 0; i < 3; i++)
            {
                string[] splitCode = SplitCode(validataCode);

                for (int j = 0; j < 2; j++)
                {
                    if (j == 0)
                    {
                        ImageBmp(out bitmap, splitCode[0]);
                    }
                    else
                    {
                        ImageBmp(out bitmap, splitCode[1]);
                    }
                    //    this.CreateImageBmp(out bitmap, splitCode[1]);
                    //this.DisposeImageBmp(ref bitmap);
                    bitmap.Save(stream, ImageFormat.Png);
                    //imageFrame.Save(string.Format("d://vali/{0}{1}.bmp", i, j));
                    encoder.AddFrame(System.Drawing.Image.FromStream(stream));
                    stream = new MemoryStream();
                    bitmap.Dispose();
                }
            }
            encoder.OutPut(ref stream);

            bitmap = null;
            stream.Close();
            stream.Dispose();

            return(stream.GetBuffer());
        }
예제 #30
0
        public void SaveGif()
        {
            DirectoryInfo dirInfo = new DirectoryInfo(savePath);

            if (!dirInfo.Exists)
            {
                return;
            }

            FileInfo[] fileInfos = dirInfo.GetFiles("*.bmp");
            if (fileInfos.Length <= 0)
            {
                return;
            }

            String gifFile = AnimationConfig.BitmapSavePath + "/" + AnimationConfig.BitmapSaveName + ".gif";

            AnimatedGifEncoder gifEncoder = new AnimatedGifEncoder();

            int deylay = (int)(100 / AnimationConfig.AnimationSpeedFactor);

            //if (deylay > 500) deylay = 500;
            //if (deylay < 20) deylay = 20;

            gifEncoder.SetDelay(deylay);
            gifEncoder.SetRepeat(0);

            bool ok = gifEncoder.Start(gifFile);

            if (!ok)
            {
                return;
            }

            DateTime begin = DateTime.Now;

            foreach (FileInfo fileInfo in fileInfos)
            {
                string filename = fileInfo.FullName;
                try
                {
                    Image img = Image.FromFile(filename);
                    gifEncoder.AddFrame(img);
                    img.Dispose();
                }
                catch (OutOfMemoryException) { }
                catch (FileNotFoundException) { }
                catch (ArgumentException) { }
            }

            gifEncoder.Finish();
            Console.Write("生成Gif耗时:" + (DateTime.Now - begin).TotalMilliseconds);
        }