Пример #1
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);
            }
        }
Пример #2
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();
        }
Пример #3
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);
        }
Пример #4
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);
            }
        }
Пример #5
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);
            }
        }
Пример #6
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();
            }
        }
Пример #7
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();
            });
        }
Пример #8
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());
        }
Пример #9
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!");
        }
Пример #10
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;
        }
Пример #11
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);
        }
Пример #12
0
        public void NeuQuantTest()
        {
            ReportStart();
            _e = new AnimatedGifEncoder();
            _e.SamplingFactor = 10;
            _e.QuantizerType  = QuantizerType.NeuQuant;
            _e.AddFrame(new GifFrame(Image.FromFile(@"images\MockOrange.jpg")));

            // TODO: add something to NUnit.Extensions to run LongRunningProcesses on a background thread
            Thread t = new Thread(DoEncode);

            t.IsBackground = true;
            t.Start();
            while (t.IsAlive)
            {
                foreach (ProgressCounter c in _e.AllProgressCounters.Values)
                {
                    WriteMessage(c.ToString());
                }
                Thread.Sleep(1000);
            }

            Image expected = Image.FromFile(@"images\MockOrange.gif");
            Image actual   = Image.FromFile("MockOrange.test.gif");

            ImageAssert.AreEqual(expected, actual);
            ReportEnd();
        }
Пример #13
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);
            }
        }
Пример #14
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 );
            //}
        }
Пример #15
0
        private void persistableOutput_ImageCaptured(object sender, ImageCapturedEventArgs e)
        {
            if (this._isRecording)
            {
                //Initialize values;
                _previousHash      = string.Empty;
                _previousTimestamp = DateTime.MinValue;
                _fileName          = e.ImageNames.FullSize;

                this._AnimatedGifEncoder = new AnimatedGifEncoder();
                this._AnimatedGifEncoder.Start(e.ImageNames.FullSize);
                this._AnimatedGifEncoder.SetDelay(PluginSettings.CaptureInterval);
                this._AnimatedGifEncoder.SetQuality(PluginSettings.EncodingQuality);
                this._AnimatedGifEncoder.SetRepeat(PluginSettings.Repeats);
                this._recordTimer.Start();
                if (PluginSettings.PlaySound)
                {
                    Beep(1000, 30);
                }
            }
            else
            {
                this._recordTimer.Stop();
                FinishCapture();
            }
        }
Пример #16
0
        /// <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;
            }
        }
Пример #17
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);
        }
Пример #18
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;
        }
Пример #19
0
Файл: Form1.cs Проект: icprog/PC
        private void button2_Click(object sender, EventArgs e)
        {
            if (srcImage.Count <= 0)
            {
                MessageBox.Show("Select picture first!");
                return;
            }

            Ispreview      = false;
            imageBox.Image = null;
            String         outputPath = "";
            SaveFileDialog sdg        = new SaveFileDialog();

            sdg.Filter = "GIF | *.gif";
            if (sdg.ShowDialog() == DialogResult.OK)
            {
                outputPath = sdg.FileName;
                if (File.Exists(outputPath))
                {
                    File.Delete(outputPath);
                }
                AnimatedGifEncoder gif = new AnimatedGifEncoder();
                tm = trackBar1.Value;
                this.button1.Enabled      = false;
                this.button2.Enabled      = false;
                this.progressBar1.Value   = 0;
                this.progressBar1.Maximum = srcImage.Count;
                startConvertThread(outputPath);
            }
        }
Пример #20
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();
        }
Пример #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>
        /// 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();
        }
Пример #23
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);
            }
        }
Пример #24
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, "文件存在,生成成功");
        }
Пример #25
0
        /// <summary>
        /// 创建GIF动画
        /// </summary>
        /// <returns>byte数组图片</returns>
        public static Stream GetGifImage()
        {
            CreateValidate();
            AnimatedGifEncoder animatedGifEncoder = new AnimatedGifEncoder();

            Stream stream = new MemoryStream();

            animatedGifEncoder.Start();
            //确保视觉残留
            //animatedGifEncoder.Delay= 10;
            animatedGifEncoder.SetRepeat(0);
            //animatedGifEncoder.SetTransparent(Color.White);
            for (int i = 0; i < 10; i++)
            {
                Bitmap bitmap;
                //创建一帧的图像
                CreateImageBmp(out bitmap);
                //生成随机线条
                DisposeImageBmp(ref bitmap);
                //输出绘图,将图像保存到指定的流
                bitmap.Save(stream, ImageFormat.Png);
                animatedGifEncoder.AddFrame(System.DrawingCore.Image.FromStream(stream));
                stream = new MemoryStream();
            }
            animatedGifEncoder.OutPut(ref stream);
            animatedGifEncoder.Finish();

            return(stream);
        }
Пример #26
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;
        }
Пример #27
0
        public void BadEncodingUsingGameboyPaletteLocal()
        {
            ReportStart();
            _e = new AnimatedGifEncoder();
            _e.ColourTableStrategy = ColourTableStrategy.UseLocal;
            _e.QuantizerType       = QuantizerType.UseSuppliedPalette;

            GifFrame frame
                = new GifFrame(Image.FromFile(@"images\smiley.bmp"));

            _e.AddFrame(frame);

            Assert.AreEqual(ColourTableStrategy.UseLocal, _e.ColourTableStrategy);
            Assert.AreEqual(QuantizerType.UseSuppliedPalette, _e.QuantizerType);

            frame.Palette = Palette.FromFile(@"ColourTables\gameboy.act");

            Assert.AreEqual(ColourTableStrategy.UseLocal, _e.ColourTableStrategy);
            Assert.AreEqual(QuantizerType.UseSuppliedPalette, _e.QuantizerType);

            _e.WriteToFile(GifFileName);

            _d = new GifDecoder(GifFileName);
            _d.Decode();

            Assert.AreEqual(ErrorState.Ok, _d.ConsolidatedState);

            ReportEnd();
        }
Пример #28
0
 public void ColourQualityTooLow()
 {
     ReportStart();
     _e = new AnimatedGifEncoder();
     _e.SamplingFactor = 0;
     Assert.AreEqual(1, _e.SamplingFactor);
     ReportEnd();
 }
Пример #29
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);
            //}
        }
Пример #30
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();
            }
        }
        /// <summary>
        /// Tests the AnimatedGifEncoder and the encoded GIF file it produces
        /// using the supplied parameters as property values.
        /// </summary>
        private void TestAnimatedGifEncoder( ColourTableStrategy strategy, 
            int colourQuality,
            Size logicalScreenSize)
        {
            _e = new AnimatedGifEncoder();

            // Check default properties set by constructor.
            Assert.AreEqual( ColourTableStrategy.UseGlobal,
                             _e.ColourTableStrategy,
                             "Colour table strategy set by constructor" );
            Assert.AreEqual( 10,
                             _e.SamplingFactor,
                             "Colour quantization quality set by constructor" );
            Assert.AreEqual( Size.Empty,
                             _e.LogicalScreenSize,
                             "Logical screen size set by constructor" );

            _e.ColourTableStrategy = strategy;
            _e.SamplingFactor = colourQuality;
            _e.LogicalScreenSize = logicalScreenSize;

            // Check property set/gets
            Assert.AreEqual( strategy,
                             _e.ColourTableStrategy,
                             "Colour table strategy property set/get" );
            Assert.AreEqual( colourQuality,
                             _e.SamplingFactor,
                             "Colour quantization quality property set/get" );
            Assert.AreEqual( logicalScreenSize,
                             _e.LogicalScreenSize,
                             "Logical screen size property get/set" );

            foreach( GifFrame thisFrame in _frames )
            {
                _e.AddFrame( thisFrame );
            }

            StackTrace t = new StackTrace();
            StackFrame f = t.GetFrame( 1 );
            string fileName
                = "Checks." + this.GetType().Name
                + "." + f.GetMethod().Name + ".gif";
            _e.WriteToFile( fileName );

            Stream s = File.OpenRead( fileName );

            // global info
            CheckGifHeader( s );
            bool shouldHaveGlobalColourTable
                = (strategy == ColourTableStrategy.UseGlobal);
            LogicalScreenDescriptor lsd
                = CheckLogicalScreenDescriptor( s, shouldHaveGlobalColourTable );

            // Only check the global colour table if there should be one
            ColourTable gct = null;
            if( shouldHaveGlobalColourTable )
            {
                gct = CheckColourTable( s, lsd.GlobalColourTableSize );
            }

            CheckExtensionIntroducer( s );
            CheckAppExtensionLabel( s );
            CheckNetscapeExtension( s, 0 );

            CheckFrame( s, gct, Bitmap1() );
            CheckFrame( s, gct, Bitmap2() );

            // end of image data
            CheckGifTrailer( s );
            CheckEndOfStream( s );
            s.Close();

            // Check the file using the decoder
            _d = new GifDecoder( fileName );
            _d.Decode();
            Assert.AreEqual( ErrorState.Ok,
                             _d.ConsolidatedState,
                             "Decoder consolidated state" );
            Assert.AreEqual( 2, _d.Frames.Count, "Decoder frame count" );
            Assert.AreEqual( shouldHaveGlobalColourTable,
                             _d.LogicalScreenDescriptor.HasGlobalColourTable,
                             "Should have global colour table" );
            Assert.AreEqual( logicalScreenSize,
                             _d.LogicalScreenDescriptor.LogicalScreenSize,
                             "Decoder logical screen size" );

            BitmapAssert.AreEqual( Bitmap1(),
                                   (Bitmap) _d.Frames[0].TheImage,
                                   "frame 0" );
            BitmapAssert.AreEqual( Bitmap2(),
                                   (Bitmap) _d.Frames[1].TheImage,
                                   "frame 1" );

            bool shouldHaveLocalColourTable = !shouldHaveGlobalColourTable;
            Assert.AreEqual( shouldHaveLocalColourTable,
                             _d.Frames[0].ImageDescriptor.HasLocalColourTable,
                             "Frame 0 has local colour table" );
            Assert.AreEqual( shouldHaveLocalColourTable,
                             _d.Frames[1].ImageDescriptor.HasLocalColourTable,
                             "Frame 0 has local colour table" );
        }
        private void TestUseSuppliedPalette( ColourTableStrategy strategy )
        {
            string globalLocal
                = strategy == ColourTableStrategy.UseGlobal
                ? "Global"
                : "Local";
            // First, create and check a series of single-frame GIFs, one for
            // each of the available colour tables.
            string[] files = Directory.GetFiles( @"ColourTables", "*.act" );
            foreach( string act in files )
            {
                string actFileWithoutExtension
                    = Path.GetFileNameWithoutExtension( act );
                _e = new AnimatedGifEncoder();
                if( strategy == ColourTableStrategy.UseGlobal )
                {
                    _e.Palette = Palette.FromFile( act );
                    Assert.AreEqual( ColourTableStrategy.UseGlobal,
                                     _e.ColourTableStrategy );
                    // QuantizerType should default to UseSuppliedPalette when
                    // the encoder's Palette property is set.
                    Assert.AreEqual( QuantizerType.UseSuppliedPalette,
                                     _e.QuantizerType );
                }
                else
                {
                    _e.ColourTableStrategy = ColourTableStrategy.UseLocal;
                    Assert.AreEqual( ColourTableStrategy.UseLocal,
                                     _e.ColourTableStrategy );
                    _e.QuantizerType = QuantizerType.UseSuppliedPalette;
                    Assert.AreEqual( QuantizerType.UseSuppliedPalette,
                                     _e.QuantizerType );
                }

                GifFrame frame
                    = new GifFrame( Image.FromFile( @"images\smiley.bmp" ) );
                if( strategy == ColourTableStrategy.UseLocal )
                {
                    frame.Palette = Palette.FromFile( act );
                }
                _e.AddFrame( frame );

                string fileName
                    = "AnimatedGifEncoderTest.UseSuppliedPalette"
                    + globalLocal
                    + "-"
                    + actFileWithoutExtension
                    + ".gif";
                _e.WriteToFile( fileName );

                _d = new GifDecoder( fileName, true );
                _d.Decode();

                Assert.AreEqual( ErrorState.Ok, _d.ConsolidatedState,
                                 actFileWithoutExtension );
                Assert.AreEqual( 1, _d.Frames.Count, actFileWithoutExtension );

                if( strategy == ColourTableStrategy.UseGlobal )
                {
                    Assert.AreEqual( true,
                                     _d.LogicalScreenDescriptor.HasGlobalColourTable,
                                     actFileWithoutExtension );
                    Assert.IsNotNull( _d.GlobalColourTable,
                                      actFileWithoutExtension );
                }
                else
                {
                    Assert.AreEqual( false,
                                     _d.LogicalScreenDescriptor.HasGlobalColourTable,
                                     actFileWithoutExtension );
                    Assert.IsNull( _d.GlobalColourTable, actFileWithoutExtension );
                }

                string expectedFileName
                    = @"images\Smiley\Smiley"
                    + "-"
                    + actFileWithoutExtension
                    + ".bmp";
                Image expected = Image.FromFile( expectedFileName );
                ImageAssert.AreEqual( expected, _d.Frames[0].TheImage, expectedFileName );
            }

            // now encode a multi-frame animation with a user-supplied palette
            _d = new GifDecoder( @"images\globe\spinning globe better 200px transparent background.gif" );
            _d.Decode();
            _e = new AnimatedGifEncoder();
            _e.QuantizerType = QuantizerType.UseSuppliedPalette;
            _e.Palette = Palette.FromFile( @"ColourTables\C64.act" );
            foreach( GifFrame f in _d.Frames )
            {
                _e.AddFrame( f );
            }
            string globeFileName
                = "AnimatedGifEncoderTest.UseSuppliedPalette"
                + globalLocal
                + ".gif";
            _e.WriteToFile( globeFileName );

            _d = new GifDecoder( globeFileName );
            _d.Decode();
            Assert.AreEqual( ErrorState.Ok, _d.ConsolidatedState );
            Assert.AreEqual( _e.Frames.Count, _d.Frames.Count );
        }
        public void Bug2892015()
        {
            ReportStart();
            _e = new AnimatedGifEncoder();

            #region create 10 random bitmaps
            Collection<Bitmap> bitmaps = new Collection<Bitmap>();
            for( int i = 0; i < 10; i++ )
            {
                Bitmap bitmap = RandomBitmap.Create( new Size( 50, 50 ),
                                                     10,
                                                     PixelFormat.Format32bppRgb );
                bitmaps.Add( bitmap );
            }
            #endregion

            DateTime startTime;
            DateTime endTime;

            #region create animation using just the first 3 (this should be quick)
            for( int i = 0; i < 3; i++ )
            {
                _e.AddFrame( new GifFrame( bitmaps[i] ) );
            }

            startTime = DateTime.Now;
            _e.WriteToFile( "2892015-1.gif" );
            endTime = DateTime.Now;
            TimeSpan runTime1 = endTime - startTime;
            WriteMessage( "Encoding 3 frames took " + runTime1 );
            #endregion

            _e.Frames.Clear();

            #region create animation using all the bitmaps (this will take longer)
            foreach( Bitmap bitmap in bitmaps )
            {
                _e.AddFrame( new GifFrame( bitmap ) );
            }

            startTime = DateTime.Now;
            _e.WriteToFile( "2892015-2.gif" );
            endTime = DateTime.Now;
            TimeSpan runTime2 = endTime - startTime;
            WriteMessage( "Encoding all " + bitmaps.Count + " frames took " + runTime2 );
            #endregion

            _e.Frames.Clear();

            #region create animation using just the first 3 (this should be quick)
            for( int i = 0; i < 3; i++ )
            {
                _e.AddFrame( new GifFrame( bitmaps[i] ) );
            }

            startTime = DateTime.Now;
            _e.WriteToFile( "2892015-3.gif" );
            endTime = DateTime.Now;
            TimeSpan runTime3 = endTime - startTime;
            WriteMessage( "Encoding 3 frames took " + runTime3 );
            #endregion

            Assert.IsTrue( runTime3 < runTime2 );
            _d = new GifDecoder( "2892015-3.gif" );
            _d.Decode();
            Assert.AreEqual( 3, _d.Frames.Count );

            ReportEnd();
        }
 public void ColourQualityTooLow()
 {
     ReportStart();
     _e = new AnimatedGifEncoder();
     _e.SamplingFactor = 0;
     Assert.AreEqual( 1, _e.SamplingFactor );
     ReportEnd();
 }
        public void CompareQuantizers()
        {
            ReportStart();

            string fileName;
            DateTime startTime;
            DateTime endTime;
            TimeSpan encodingTime;

            // Test actual quantization using image with 256+ colours.
            string bitmapFileName = "images/" + TestFixtureName
                                   + "." + TestCaseName + ".bmp";

            Bitmap b = new Bitmap( bitmapFileName );

            for( int q = 1; q <= 20; q++ )
            {
                _e = new AnimatedGifEncoder();
                _e.QuantizerType = QuantizerType.NeuQuant;
                _e.SamplingFactor = q;
                _e.AddFrame( new GifFrame( b ) );
                fileName = TestFixtureName + "." + TestCaseName + ".NeuQuant." + q + ".gif";
                startTime = DateTime.Now;
                _e.WriteToFile( fileName );
                endTime = DateTime.Now;
                encodingTime = endTime - startTime;
                WriteMessage( "Encoding with quantization using NeuQuant, quality="
                              + q + " took " + encodingTime );
                _d = new GifDecoder( fileName );
                _d.Decode();
                Assert.AreEqual( ErrorState.Ok, _d.ConsolidatedState, "Quality " + q );
                Assert.AreEqual( 1, _d.Frames.Count, "Quality " + q );
                // FIXME: NeuQuant quantizer reducing to 180 colours instead of 256 colours
                // TODO: Check for exactly 256 colours once Octree quantizer returns 256-colour images
            //				Assert.AreEqual( 256, ImageTools.GetDistinctColours( colours ).Count );
                Assert.LessOrEqual( ImageTools.GetDistinctColours( _d.Frames[0].TheImage ).Count, 256 );
                for( int tolerance = 0; tolerance < 256; tolerance++ )
                {
                    try
                    {
                        ImageAssert.AreEqual( b,
                                              _d.Frames[0].TheImage,
                                              tolerance,
                                              "Quality " + q );
                        WriteMessage( "Quality " + q
                                     + " required tolerance " + tolerance );
                        break;
                    }
                    catch( AssertionExtensionException )
                    {
                        if( tolerance == 255 )
                        {
                            throw;
                        }
                    }
                }
            }

            _e = new AnimatedGifEncoder();
            _e.QuantizerType = QuantizerType.Octree;
            _e.AddFrame( new GifFrame( b ) );
            fileName = TestFixtureName + "." + TestCaseName + ".Octree.gif";
            startTime = DateTime.Now;
            _e.WriteToFile( fileName );
            endTime = DateTime.Now;
            encodingTime = endTime - startTime;
            WriteMessage( "Encoding with quantization using Octree took " + encodingTime );
            _d = new GifDecoder( fileName );
            _d.Decode();
            Assert.AreEqual( ErrorState.Ok, _d.ConsolidatedState );
            Assert.AreEqual( 1, _d.Frames.Count );
            // FIXME: Octree quantizer should return a 256-colour image here
            //			Assert.AreEqual( 256, ImageTools.GetDistinctColours( colours2 ).Count );
            Assert.LessOrEqual( ImageTools.GetDistinctColours( _d.Frames[0].TheImage ).Count, 256 );
            for( int tolerance = 0; tolerance < 256; tolerance++ )
            {
                try
                {
                    ImageAssert.AreEqual( b,
                                          _d.Frames[0].TheImage,
                                          tolerance,
                                          "Octree" );
                    WriteMessage( "Octree quantization required tolerance "
                                 + tolerance );
                    break;
                }
                catch( AssertionExtensionException )
                {
                    if( tolerance == 255 )
                    {
                        throw;
                    }
                }
            }

            // re-encoding an existing GIF should not cause quantization
            _d = new GifDecoder( @"images\globe\spinning globe better 200px transparent background.gif" );
            _d.Decode();

            _e = new AnimatedGifEncoder();
            // NB OctreeQuantizer does not support global colour tables (yet!)
            _e.ColourTableStrategy = ColourTableStrategy.UseLocal;
            foreach( GifFrame f in _d.Frames )
            {
                _e.AddFrame( new GifFrame( f.TheImage ) );
            }

            fileName = "NeuQuant.gif";
            _e.QuantizerType = QuantizerType.NeuQuant;
            startTime = DateTime.Now;
            _e.WriteToFile( fileName );
            endTime = DateTime.Now;
            encodingTime = endTime - startTime;
            WriteMessage( "Encoding without quantization using NeuQuant took " + encodingTime );

            fileName = "Octree.gif";
            _e.QuantizerType = QuantizerType.Octree;
            startTime = DateTime.Now;
            _e.WriteToFile( fileName );
            endTime = DateTime.Now;
            encodingTime = endTime - startTime;
            WriteMessage( "Encoding without quantization using Octree took " + encodingTime );

            GifDecoder nqDecoder = new GifDecoder( "NeuQuant.gif" );
            nqDecoder.Decode();
            GifDecoder otDecoder = new GifDecoder( "Octree.gif" );
            otDecoder.Decode();
            Assert.AreEqual( nqDecoder.Frames.Count, otDecoder.Frames.Count );
            for( int i = 0; i < nqDecoder.Frames.Count; i++ )
            {
                ImageAssert.AreEqual( nqDecoder.Frames[i].TheImage,
                                      otDecoder.Frames[i].TheImage,
                                      "frame " + i );
            }

            ReportEnd();
        }
Пример #36
0
        public void TransparencyTest()
        {
            ReportStart();
            Color noColour = Color.FromArgb( 0, 0, 0, 0 ); // note alpha of 0
            Color blue = Color.FromArgb( 0, 0, 255 );
            Color transparent = Color.FromArgb( 100, 100, 100 );
            _encoder = new AnimatedGifEncoder();
            _encoder.Transparent = transparent;

            // transparent | transparent
            // -------------------------
            // blue        | blue
            Bitmap bitmap = new Bitmap( 2, 2 );
            bitmap.SetPixel( 0, 0, transparent );
            bitmap.SetPixel( 1, 0, transparent );
            bitmap.SetPixel( 0, 1, blue );
            bitmap.SetPixel( 1, 1, blue );
            _frame = new GifFrame( bitmap );
            _encoder.AddFrame( _frame );

            // encode and decode
            string filename = "GifFrameTest.TransparencyTest.gif";
            _encoder.WriteToFile( filename );
            _decoder = new GifDecoder( filename );
            _decoder.Decode();
            Assert.AreEqual( ErrorState.Ok, _decoder.ConsolidatedState );

            // Result should be:
            // black | black
            // -------------
            // blue  | blue

            Bitmap actual = (Bitmap) _decoder.Frames[0].TheImage;
            Assert.AreEqual( noColour, actual.GetPixel( 0, 0 ) );
            Assert.AreEqual( noColour, actual.GetPixel( 1, 0 ) );
            Assert.AreEqual( blue, actual.GetPixel( 0, 1 ) );
            Assert.AreEqual( blue, actual.GetPixel( 1, 1 ) );

            ReportEnd();
        }
 public void DecodeEncodeGlobeLocal()
 {
     ReportStart();
     string filename = @"images/globe/spinning globe better 200px transparent background.gif";
     _d = new GifDecoder( filename );
     _d.Decode();
     _e = new AnimatedGifEncoder();
     _e.ColourTableStrategy = ColourTableStrategy.UseLocal;
     foreach( GifFrame f in _d.Frames )
     {
         _e.AddFrame( new GifFrame( f.TheImage ) );
     }
     MemoryStream s = new MemoryStream();
     _e.WriteToStream( s );
     s.Seek( 0, SeekOrigin.Begin );
     _d = new GifDecoder( s );
     _d.Decode();
     CheckFrames();
     ReportEnd();
 }
 public void DecodeEncodeSmileyLocal()
 {
     ReportStart();
     string filename = @"images/smiley/smiley.gif";
     _d = new GifDecoder( filename );
     _d.Decode();
     _e = new AnimatedGifEncoder();
     _e.ColourTableStrategy = ColourTableStrategy.UseLocal;
     foreach( GifFrame f in _d.Frames )
     {
         _e.AddFrame( new GifFrame( f.TheImage ) );
     }
     MemoryStream s = new MemoryStream();
     _e.WriteToStream( s );
     s.Seek( 0, SeekOrigin.Begin );
     _d = new GifDecoder( s );
     _d.Decode();
     CheckFrames();
     ReportEnd();
 }
        public void NeuQuantTest()
        {
            ReportStart();
            _e = new AnimatedGifEncoder();
            _e.SamplingFactor = 10;
            _e.QuantizerType = QuantizerType.NeuQuant;
            _e.AddFrame( new GifFrame( Image.FromFile( @"images\MockOrange.jpg" ) ) );

            // TODO: add something to NUnit.Extensions to run LongRunningProcesses on a background thread
            Thread t = new Thread( DoEncode );
            t.IsBackground = true;
            t.Start();
            while( t.IsAlive )
            {
                foreach( ProgressCounter c in _e.AllProgressCounters.Values )
                {
                    WriteMessage( c.ToString() );
                }
                Thread.Sleep( 1000 );
            }

            Image expected = Image.FromFile( @"images\MockOrange.gif" );
            Image actual = Image.FromFile( "MockOrange.test.gif" );
            ImageAssert.AreEqual( expected, actual );
            ReportEnd();
        }
        public void WikipediaExampleTest()
        {
            ReportStart();
            _e = new AnimatedGifEncoder();
            GifFrame frame = new GifFrame( WikipediaExample.ExpectedBitmap );
            frame.Delay = WikipediaExample.DelayTime;
            _e.AddFrame( frame );

            // TODO: some way of creating/testing a UseLocal version of WikipediaExample
            string fileName = "WikipediaExampleUseGlobal.gif";
            _e.WriteToFile( fileName );
            Stream s = File.OpenRead( fileName );

            int code;

            // check GIF header
            GifHeader gh = new GifHeader( s );
            Assert.AreEqual( ErrorState.Ok, gh.ConsolidatedState );

            // check logical screen descriptor
            LogicalScreenDescriptor lsd = new LogicalScreenDescriptor( s );
            Assert.AreEqual( ErrorState.Ok, lsd.ConsolidatedState );
            WikipediaExample.CheckLogicalScreenDescriptor( lsd );

            // read global colour table
            ColourTable gct
                = new ColourTable( s, WikipediaExample.GlobalColourTableSize );
            Assert.AreEqual( ErrorState.Ok, gct.ConsolidatedState );
            // cannot compare global colour table as different encoders will
            // produce difference colour tables.
            //			WikipediaExample.CheckGlobalColourTable( gct );

            // check for extension introducer
            code = ExampleComponent.CallRead( s );
            Assert.AreEqual( GifComponent.CodeExtensionIntroducer, code );

            // check for app extension label
            code = ExampleComponent.CallRead( s );
            Assert.AreEqual( GifComponent.CodeApplicationExtensionLabel, code );

            // check netscape extension
            ApplicationExtension ae = new ApplicationExtension( s );
            Assert.AreEqual( ErrorState.Ok, ae.ConsolidatedState );
            NetscapeExtension ne = new NetscapeExtension( ae );
            Assert.AreEqual( ErrorState.Ok, ne.ConsolidatedState );
            Assert.AreEqual( 0, ne.LoopCount );

            // check for extension introducer
            code = ExampleComponent.CallRead( s );
            Assert.AreEqual( GifComponent.CodeExtensionIntroducer, code );

            // check for gce label
            code = ExampleComponent.CallRead( s );
            Assert.AreEqual( GifComponent.CodeGraphicControlLabel, code );

            // check graphic control extension
            GraphicControlExtension gce = new GraphicControlExtension( s );
            Assert.AreEqual( ErrorState.Ok, gce.ConsolidatedState );
            WikipediaExample.CheckGraphicControlExtension( gce );

            // check for image separator
            code = ExampleComponent.CallRead( s );
            Assert.AreEqual( GifComponent.CodeImageSeparator, code );

            // check for image descriptor
            ImageDescriptor id = new ImageDescriptor( s );
            Assert.AreEqual( ErrorState.Ok, id.ConsolidatedState );
            WikipediaExample.CheckImageDescriptor( id );

            // read, decode and check image data
            // Cannot compare encoded LZW data directly as different encoders
            // will create different colour tables, so even if the bitmaps are
            // identical, the colour indices will be different
            int pixelCount = WikipediaExample.FrameSize.Width
                            * WikipediaExample.FrameSize.Height;
            TableBasedImageData tbid = new TableBasedImageData( s, pixelCount );
            for( int y = 0; y < WikipediaExample.LogicalScreenSize.Height; y++ )
            {
                for( int x = 0; x < WikipediaExample.LogicalScreenSize.Width; x++ )
                {
                    int i = (y * WikipediaExample.LogicalScreenSize.Width) + x;
                    Assert.AreEqual( WikipediaExample.ExpectedBitmap.GetPixel( x, y ),
                                     gct[tbid.Pixels[i]],
                                     "X: " + x + ", Y: " + y );
                }
            }

            // Check for block terminator after image data
            code = ExampleComponent.CallRead( s );
            Assert.AreEqual( 0x00, code );

            // check for GIF trailer
            code = ExampleComponent.CallRead( s );
            Assert.AreEqual( GifComponent.CodeTrailer, code );

            // check we're at the end of the stream
            code = ExampleComponent.CallRead( s );
            Assert.AreEqual( -1, code );
            s.Close();

            _d = new GifDecoder( fileName );
            _d.Decode();
            Assert.AreEqual( ErrorState.Ok, _d.ConsolidatedState );
            BitmapAssert.AreEqual( WikipediaExample.ExpectedBitmap,
                                  (Bitmap) _d.Frames[0].TheImage,
                                   "" );
            ReportEnd();
        }
 public void WriteToStreamNoFramesTest()
 {
     ReportStart();
     _e = new AnimatedGifEncoder();
     MemoryStream s = new MemoryStream();
     try
     {
         _e.WriteToStream( s );
     }
     catch( InvalidOperationException ex )
     {
         string message
             = "The AnimatedGifEncoder has no frames to write!";
         StringAssert.Contains( message, ex.Message );
         ReportEnd();
         throw;
     }
 }
 public void ProfileTest()
 {
     ReportStart();
     _encoder = new AnimatedGifEncoder();
     _encoder.AddFrame( new GifFrame( RandomBitmap.Create( new Size( 500, 500 ),
                                                     10,
                                                     PixelFormat.Format32bppArgb ) ) );
     System.Threading.Thread t
         = new System.Threading.Thread( EncodeBigFile );
     t.IsBackground = true;
     t.Start();
     while( t.IsAlive )
     {
         foreach( ProgressCounter counter in _encoder.AllProgressCounters.Values )
         {
             WriteMessage( counter.ToString() );
         }
         System.Threading.Thread.Sleep( 100 );
     }
     ReportEnd();
 }
        public void BadEncodingUsingGameboyPaletteLocal()
        {
            ReportStart();
            _e = new AnimatedGifEncoder();
            _e.ColourTableStrategy = ColourTableStrategy.UseLocal;
            _e.QuantizerType = QuantizerType.UseSuppliedPalette;

            GifFrame frame
                = new GifFrame( Image.FromFile( @"images\smiley.bmp" ) );
            _e.AddFrame( frame );

            Assert.AreEqual( ColourTableStrategy.UseLocal, _e.ColourTableStrategy );
            Assert.AreEqual( QuantizerType.UseSuppliedPalette, _e.QuantizerType );

            frame.Palette = Palette.FromFile( @"ColourTables\gameboy.act" );

            Assert.AreEqual( ColourTableStrategy.UseLocal, _e.ColourTableStrategy );
            Assert.AreEqual( QuantizerType.UseSuppliedPalette, _e.QuantizerType );

            _e.WriteToFile( GifFileName );

            _d = new GifDecoder( GifFileName );
            _d.Decode();

            Assert.AreEqual( ErrorState.Ok, _d.ConsolidatedState );

            ReportEnd();
        }
        private void TryDifferentPixelFormats()
        {
            Size size = new Size( 50, 50 );
            int blockiness = 10;
            PixelFormat[] pixelFormats = new PixelFormat[]
            {
                PixelFormat.Format16bppArgb1555,
                PixelFormat.Format16bppRgb555,
                PixelFormat.Format16bppRgb565,
                PixelFormat.Format24bppRgb,
                PixelFormat.Format32bppArgb,
                PixelFormat.Format32bppPArgb,
                PixelFormat.Format32bppRgb,
                PixelFormat.Format48bppRgb,
                PixelFormat.Format64bppArgb,
                PixelFormat.Format64bppPArgb,
            };
            foreach( PixelFormat pf in pixelFormats )
            {
                string formatName = pf.ToString();

                _encoder = new AnimatedGifEncoder();
                for( int i = 0; i < 10; i++ )
                {
                    Bitmap bitmap = RandomBitmap.Create( size,
                                                         blockiness,
                                                         pf );
                    _encoder.AddFrame( new GifFrame( bitmap ) );
                }

                DateTime startTime = DateTime.Now;
                _encoder.WriteToFile( formatName + ".gif" );
                DateTime endTime = DateTime.Now;
                TimeSpan timeToEncode8bit = endTime - startTime;
                WriteMessage( "Encoding " + formatName + " took " + timeToEncode8bit );
            }
        }