private WriteableBitmap DecodeGif(MemoryStream stream)
        {
            stream.Seek(0, SeekOrigin.Begin);

            var gd = new GifDecoder();
            int status = gd.Read(stream);
            if (status == GifDecoder.STATUS_OK)
            {
                return gd.GetImage();
            }

            return null;
        }
Example #2
0
        public static byte[] GetThumbnailGIF89a(Stream stream, Size min, Size thumb)
        {
            long       offset  = stream.Position;
            GifDecoder decoder = new GifDecoder();

            decoder.Read(stream);
            Size sz = decoder.GetFrameSize();

            stream.Seek(offset, SeekOrigin.Begin);

            if (min != null && sz.Width < min.Width && sz.Height < min.Height)
            {
                throw new InvalidImageSizeException(
                          string.Empty, sz, min);
            }

            return(GetResizedImageBytesGIF89a(decoder, stream, thumb, s_ImageQuality));
        }
Example #3
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();
        }
Example #4
0
        public static ImageResult FromStream(Stream stream, ColorComponents?requiredComponents = null,
                                             bool use8BitsPerChannel = true)
        {
            ImageResult result = null;

            if (JpgDecoder.Test(stream))
            {
                result = JpgDecoder.Decode(stream, requiredComponents);
            }
            else if (PngDecoder.Test(stream))
            {
                result = PngDecoder.Decode(stream, requiredComponents);
            }
            else if (BmpDecoder.Test(stream))
            {
                result = BmpDecoder.Decode(stream, requiredComponents);
            }
            else if (GifDecoder.Test(stream))
            {
                result = GifDecoder.Decode(stream, requiredComponents);
            }
            else if (PsdDecoder.Test(stream))
            {
                result = PsdDecoder.Decode(stream, requiredComponents);
            }
            else if (TgaDecoder.Test(stream))
            {
                result = TgaDecoder.Decode(stream, requiredComponents);
            }

            if (result == null)
            {
                Decoder.stbi__err("unknown image type");
            }

            if (use8BitsPerChannel && result.BitsPerChannel != 8)
            {
                result.Data = Conversion.stbi__convert_16_to_8(result.Data, result.Width, result.Height,
                                                               (int)result.ColorComponents);
            }

            return(result);
        }
Example #5
0
        public MainWindow()
        {
            InitializeComponent();

            Task.Run(async() =>
            {
                var gifImage =
                    await Dispatcher.InvokeAsync(() => GifDecoder.Decode("1.gif"));
                foreach (var temp in gifImage.Frames)
                {
                    Dispatcher.Invoke(() =>
                    {
                        //Image.Source = BitmapToImageSource(temp.Image);
                        Image.Source = temp.Image;
                    });
                    await Task.Delay(TimeSpan.FromMilliseconds(temp.Delay * 10));
                }
            });
        }
Example #6
0
        /// <summary>
        /// 把Gif文件转成Png文件,放在directory目录下
        /// </summary>
        /// <param name="file"></param>
        /// <param name="directory"></param>
        /// <returns></returns>
        public static void GifToPngs(string giffile, string directory)
        {
            GifDecoder gifDecoder = new GifDecoder();

            directory += "\\";
            if (!Directory.Exists(directory))
            {
                Directory.CreateDirectory(directory);
            }
            //读取
            gifDecoder.Read(giffile);
            for (int i = 0, count = gifDecoder.GetFrameCount(); i < count; i++)
            {
                Image frame = gifDecoder.GetFrame(i);  // frame i
                frame.Save(directory + "\\" + i.ToString("d2") + ".png", ImageFormat.Png);
                //转成jpg
                //frame.Save(directory + "\\" + i.ToString("d2") + ".jpg", ImageFormat.Jpeg);
            }
        }
Example #7
0
        public unsafe void Decode_NonTerminatedFinalFrame()
        {
            var testFile = TestFile.Create(TestImages.Gif.Rings);

            int length = testFile.Bytes.Length - 2;

            fixed(byte *data = testFile.Bytes.AsSpan(0, length))
            {
                using (var stream = new UnmanagedMemoryStream(data, length))
                {
                    var decoder = new GifDecoder();

                    using (Image <Rgba32> image = decoder.Decode <Rgba32>(Configuration.Default, stream))
                    {
                        Assert.Equal((200, 200), (image.Width, image.Height));
                    }
                }
            }
        }
Example #8
0
        async Task <FFGifDrawable> PlatformGenerateGifImageAsync(string path, ImageSource source, Stream imageData, ImageInformation imageInformation, bool enableTransformations, bool isPlaceholder)
        {
            if (imageData == null)
            {
                throw new ArgumentNullException(nameof(imageData));
            }

            ThrowIfCancellationRequested();

            try
            {
                int downsampleWidth  = 0;
                int downsampleHeight = 0;

                if (Parameters.DownSampleSize != null && (Parameters.DownSampleSize.Item1 > 0 || Parameters.DownSampleSize.Item2 > 0))
                {
                    downsampleWidth  = Parameters.DownSampleSize.Item1;
                    downsampleHeight = Parameters.DownSampleSize.Item2;
                }

                if (Parameters.DownSampleUseDipUnits)
                {
                    downsampleWidth  = downsampleWidth.DpToPixels();
                    downsampleHeight = downsampleHeight.DpToPixels();
                }

                var gifDecoder = new GifDecoder(downsampleWidth, downsampleHeight, (bmp) =>
                {
                    return(PlatformTransformAsync(path, source, enableTransformations, isPlaceholder, bmp));
                });

                await gifDecoder.ReadGifAsync(imageData);

                ThrowIfCancellationRequested();
                var bitmap = gifDecoder.GetBitmap();
                ThrowIfCancellationRequested();
                return(new FFGifDrawable(Context.Resources, bitmap, gifDecoder));
            }
            finally
            {
                imageData.TryDispose();
            }
        }
        public void SetSource(Stream stream)
        {
            Stream = stream;

            if (Stream == null)
            {
                //throw new InvalidDataException("Missing valid URI or Stream.");
                return;
            }

            _gifDecoder = new GifDecoder(Stream);
            _bgWorker   = new GifBackgroundWorker(_gifDecoder);
            var pixSize = new PixelSize(_gifDecoder.Header.Dimensions.Width, _gifDecoder.Header.Dimensions.Height);

            _targetBitmap = new WriteableBitmap(pixSize, new Vector(96, 96), PixelFormat.Bgra8888, AlphaFormat.Opaque);
            _bgWorker.CurrentFrameChanged += FrameChanged;
            GifPixelSize = pixSize;
            Run();
        }
Example #10
0
        //反转GIF动画
        private void buttonReverseGIF_Click(object sender, EventArgs e)
        {
            decimal decDelayTimes = numericUpDown_DelayTimes.Value;
            string  strFileName   = this.textBox_SelectGIFPath.Text;

            if (strFileName.Length <= 0)
            {
                MessageBox.Show("未选择要反序的文件!请选择【选择GIF文件】");
                return;
            }
            /* extract Gif */

            string        outputPath = Path.GetTempPath();
            List <string> strList    = GetFrames(strFileName, outputPath);
            GifDecoder    gifDecoder = new GifDecoder();

            gifDecoder.Read(strFileName);
            //             int count = gifDecoder.GetFrameCount();
            //             List<string> strList = new List<string>();
            //             for (int i = 0; i < count; i++)
            //             {
            //                 Image frame = gifDecoder.GetFrame(i);  // frame i
            //                 strList[i] = outputPath + Guid.NewGuid().ToString() + ".png";
            //                 frame.Save(strList[i], ImageFormat.Png);
            //                 frame.Dispose();
            //             }
            strList.Reverse();
            String             outputFilePath = strFileName + ".gif";
            AnimatedGifEncoder age            = new AnimatedGifEncoder();

            age.Start(outputFilePath);
            age.SetDelay(gifDecoder.GetDelay(0));
            //-1:no repeat,0:always repeat
            age.SetRepeat(0);
            for (int i = 0; i < strList.Count; i++)
            {
                age.AddFrame(Image.FromFile(strList[i]));
            }
            age.Finish();

            MessageBox.Show("反序完成,文件保存在" + outputFilePath + "目录!");
        }
        public void Encode_PreservesTextData()
        {
            var decoder  = new GifDecoder();
            var testFile = TestFile.Create(TestImages.Gif.LargeComment);

            using (Image <Rgba32> input = testFile.CreateRgba32Image(decoder))
                using (var memoryStream = new MemoryStream())
                {
                    input.Save(memoryStream, new GifEncoder());
                    memoryStream.Position = 0;

                    using (Image <Rgba32> image = decoder.Decode <Rgba32>(Configuration.Default, memoryStream))
                    {
                        GifMetadata metadata = image.Metadata.GetGifMetadata();
                        Assert.Equal(2, metadata.Comments.Count);
                        Assert.Equal(new string('c', 349), metadata.Comments[0]);
                        Assert.Equal("ImageSharp", metadata.Comments[1]);
                    }
                }
        }
Example #12
0
 public void PositionDecodedFrameSetTest()
 {
     ReportStart();
     _decoder = new GifDecoder(@"images\smiley\smiley.gif");
     _decoder.Decode();
     _frame = _decoder.Frames[0];
     try
     {
         _frame.Position = new Point(1, 1);
     }
     catch (InvalidOperationException ex)
     {
         string message
             = "This GifFrame was returned by a GifDecoder so this "
               + "property is read-only";
         StringAssert.Contains(message, ex.Message);
         ReportEnd();
         throw;
     }
 }
Example #13
0
        public static ImageInfo?FromStream(Stream stream)
        {
            var info = JpgDecoder.Info(stream);

            if (info != null)
            {
                return(info);
            }

            info = PngDecoder.Info(stream);
            if (info != null)
            {
                return(info);
            }

            info = GifDecoder.Info(stream);
            if (info != null)
            {
                return(info);
            }

            info = BmpDecoder.Info(stream);
            if (info != null)
            {
                return(info);
            }

            info = PsdDecoder.Info(stream);
            if (info != null)
            {
                return(info);
            }

            info = TgaDecoder.Info(stream);
            if (info != null)
            {
                return(info);
            }

            return(null);
        }
Example #14
0
        /// <summary>
        /// Creates a deep copy of an image allowing you to set the pixel format.
        /// Disposing of the original is the responsibility of the user.
        /// <remarks>
        /// Unlike the native <see cref="Image.Clone"/> method this also copies animation frames.
        /// </remarks>
        /// </summary>
        /// <param name="source">The source image to copy.</param>
        /// <param name="animationProcessMode">The process mode for frames in animated images.</param>
        /// <param name="format">The <see cref="PixelFormat"/> to set the copied image to.</param>
        /// <param name="preserveExifData">Whether to preserve exif metadata. Defaults to false.</param>
        /// <returns>
        /// The <see cref="Image"/>.
        /// </returns>
        public static Image Copy(this Image source, AnimationProcessMode animationProcessMode, PixelFormat format = PixelFormat.Format32bppPArgb, bool preserveExifData = false)
        {
            if (source.RawFormat.Equals(ImageFormat.Gif))
            {
                // Read from the correct first frame when performing additional processing
                source.SelectActiveFrame(FrameDimension.Time, 0);
                var decoder = new GifDecoder(source, animationProcessMode);
                var encoder = new GifEncoder(null, null, decoder.LoopCount);

                // Have to use Octree here, there's no way to inject it.
                var quantizer = new OctreeQuantizer();
                for (var i = 0; i < decoder.FrameCount; i++)
                {
                    var frame = decoder.GetFrame(source, i);
                    frame.Image = quantizer.Quantize(((Bitmap)frame.Image).Clone(new Rectangle(0, 0, frame.Image.Width, frame.Image.Height), format));
                    ((Bitmap)frame.Image).SetResolution(source.HorizontalResolution, source.VerticalResolution);
                    encoder.AddFrame(frame);
                }

                return(encoder.Save());
            }

            // Create a new image and copy it's pixels.
            var copy = new Bitmap(source.Width, source.Height, format);

            copy.SetResolution(source.HorizontalResolution, source.VerticalResolution);
            using (var graphics = Graphics.FromImage(copy))
            {
                graphics.DrawImageUnscaled(source, 0, 0);
            }

            if (preserveExifData)
            {
                foreach (var item in source.PropertyItems)
                {
                    copy.SetPropertyItem(item);
                }
            }

            return(copy);
        }
Example #15
0
        public static byte[] GetResizedImageBytesGIF89a(GifDecoder originalimage, Stream stream, Size ts, int quality)
        {
            Size sz = originalimage.GetFrameSize();

            if (sz.Height > ts.Height || sz.Width > ts.Width)
            {
                MemoryStream ms = new MemoryStream();
                AnimatedGifEncoder.Resize(originalimage, ms, ts.Width, ts.Height, quality);
                ms.Flush();
                byte[]       result       = new byte[ms.Length];
                MemoryStream resultstream = new MemoryStream(result);
                ms.WriteTo(resultstream);
                return(result);
            }
            else
            {
                stream.Seek(0, SeekOrigin.Begin);
                BinaryReader sr = new BinaryReader(stream);
                return(sr.ReadBytes((int)stream.Length));
            }
        }
Example #16
0
        public static IEnumerable <Bitmap> LoadSpritesFromFile(string fileName)
        {
            // We have to use this stream code because using "new Bitmap(filename)"
            // keeps the file open until the Bitmap is disposed
            FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read);
            Bitmap     loadedBmp  = (Bitmap)Bitmap.FromStream(fileStream);

            fileStream.Close();

            // Unfortunately the Bitmap.Clone method will crash later due to
            // a .NET bug when it's loaded from a stream. Therefore we need
            // to make a fresh copy.
            loadedBmp = Utilities.CreateCopyOfBitmapPreservingColourDepth(loadedBmp);

            //Bitmap loadedBmp = new Bitmap(fileName);
            if ((System.IO.Path.GetExtension(fileName).ToLower() == ".gif") &&
                (loadedBmp.PixelFormat != PixelFormat.Format8bppIndexed))
            {
                // The .NET Bitmap class has a bug, whereby it will convert
                // animated gifs to 32-bit when it loads them. This causes
                // us an issue, so use the custom GifDecoder instead when
                // this happens.
                loadedBmp.Dispose();
                GifDecoder decoder = new GifDecoder();

                if (decoder.Read(fileName) != GifDecoder.STATUS_OK)
                {
                    throw new AGS.Types.InvalidDataException("Unable to load GIF");
                }

                for (int i = 0; i < decoder.GetFrameCount(); i++)
                {
                    yield return(decoder.GetFrame(i));
                }
            }
            else
            {
                yield return(loadedBmp);
            }
        }
Example #17
0
        public void SetSource(object newValue)
        {
            var sourceUri = newValue as Uri;
            var sourceStr = newValue as Stream;

            Stream stream = null;

            if (sourceUri != null)
            {
                _streamCanDispose = true;
                this.Progress     = new Progress <int>();

                if (sourceUri.OriginalString.Trim().StartsWith("resm"))
                {
                    var assetLocator = AvaloniaLocator.Current.GetService <IAssetLoader>();
                    stream = assetLocator.Open(sourceUri);
                }
            }
            else if (sourceStr != null)
            {
                stream = sourceStr;
            }
            else
            {
                throw new InvalidDataException("Missing valid URI or Stream.");
            }

            Stream           = stream;
            this._gifDecoder = new GifDecoder(Stream);
            this._bgWorker   = new GifBackgroundWorker(_gifDecoder);
            var pixSize = new PixelSize(_gifDecoder.Header.Dimensions.Width, _gifDecoder.Header.Dimensions.Height);

            this._targetBitmap = new WriteableBitmap(pixSize, new Vector(96, 96), PixelFormat.Bgra8888);

            TargetControl.Source = _targetBitmap;
            //TargetControl.DetachedFromVisualTree += delegate { this.Dispose(); };
            _bgWorker.CurrentFrameChanged += FrameChanged;

            Run();
        }
        /// <summary>
        /// Creates a copy of an image allowing you to set the pixel format.
        /// Disposing of the original is the responsibility of the user.
        /// <remarks>
        /// Unlike the native <see cref="Image.Clone"/> method this also copies animation frames.
        /// </remarks>
        /// </summary>
        /// <param name="source">The source image to copy.</param>
        /// <param name="format">The <see cref="PixelFormat"/> to set the copied image to.</param>
        /// <returns>
        /// The <see cref="Image"/>.
        /// </returns>
        public static Image Copy(this Image source, PixelFormat format = PixelFormat.Format32bppPArgb)
        {
            if (FormatUtilities.IsAnimated(source))
            {
                // TODO: Ensure that we handle other animated types.
                GifDecoder decoder = new GifDecoder(source);
                GifEncoder encoder = new GifEncoder(null, null, decoder.LoopCount);
                foreach (GifFrame frame in decoder.GifFrames)
                {
                    frame.Image = ((Bitmap)frame.Image).Clone(new Rectangle(0, 0, frame.Image.Width, frame.Image.Height), format);
                    ((Bitmap)frame.Image).SetResolution(source.HorizontalResolution, source.VerticalResolution);
                    encoder.AddFrame(frame);
                }

                return(encoder.Save());
            }

            Bitmap copy = ((Bitmap)source).Clone(new Rectangle(0, 0, source.Width, source.Height), format);

            copy.SetResolution(source.HorizontalResolution, source.VerticalResolution);
            return(copy);
        }
Example #19
0
        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();
        }
Example #20
0
        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();
        }
Example #21
0
        public void Bug2940635()
        {
            ReportStart();
            string gifName
                = @"images\Bug2940635\Bug2940635TransparentColourIndexOutOfRangeException.gif";

            _decoder = new GifDecoder(gifName);
            _decoder.Decode();

            string bmpName;
            Image  expectedBitmap;
            Image  actualBitmap;

            for (int i = 0; i < _decoder.Frames.Count; i++)
            {
                actualBitmap   = _decoder.Frames[i].TheImage;
                bmpName        = gifName + ".frame " + i + ".bmp";
                expectedBitmap = Bitmap.FromFile(bmpName);
                ImageAssert.AreEqual(expectedBitmap, actualBitmap, "Frame " + i);
            }
            ReportEnd();
        }
Example #22
0
        public void ShowGif(string filePath)
        {
            if (!System.IO.Path.IsPathRooted(filePath))
            {
                filePath = System.IO.Path.Combine(Application.dataPath, filePath);
            }

            GifDecoder decoder = new GifDecoder();

            m_Image = new GifImage();

            DecodeWorker worker = new DecodeWorker(m_WorkerPriority)
            {
                m_Decoder      = decoder,
                m_FilePath     = filePath,
                m_Image        = m_Image,
                OnDecodeFinish = OnDecodeFinish
            };

            m_State = State.Decoding;
            worker.Start();
        }
Example #23
0
        public static bool GifToImage(string outPath, string gifFileName)
        {
            try
            {
                /* extract Gif */
                GifDecoder gifDecoder = new GifDecoder();
                gifDecoder.Read(gifFileName);
                for (int i = 0, count = gifDecoder.GetFrameCount(); i < count; i++)
                {
                    Image frame = gifDecoder.GetFrame(i); // frame i
                    frame.Save(outPath + Guid.NewGuid().ToString()
                               + ".png", ImageFormat.Png);
                    frame.Dispose();
                }

                return(true);
            }
            catch
            {
                return(false);
            }
        }
Example #24
0
        static void Main(string[] args)
        {
            /* create Gif */
            //you should replace filepath
            string folder = "C:/Users/cardman/Documents/Visual Studio 2015/Projects/Gif/Example/bolt/";

            //String [] imageFilePaths = new String[]{"G:\\01.png"};
            String[] imageFilePaths = new String[] {
                folder + "0.png", folder + "1.png", folder + "2.png",
                folder + "3.png", folder + "4.png", folder + "5.png",
                folder + "6.png", folder + "7.png", folder + "8.png", folder + "9.png"
            };
            //String outputFilePath = "G:\\test.gif";
            String             outputFilePath = folder + "bolt.gif";
            AnimatedGifEncoder e = new AnimatedGifEncoder();

            e.Start(outputFilePath);
            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 = "G:\\";
            string     outputPath = folder;
            GifDecoder gifDecoder = new GifDecoder();

            //gifDecoder.Read( "G:\\test.gif" );
            gifDecoder.Read(outputFilePath);
            for (int i = 0, count = gifDecoder.GetFrameCount(); i < count; i++)
            {
                Image frame = gifDecoder.GetFrame(i);                    // frame i
                frame.Save(outputPath + "_" + i + ".png", ImageFormat.Png);
            }
        }
Example #25
0
        public static int GetFrameCountEstimateFromFile(string fileName)
        {
            if (!File.Exists(fileName))
            {
                return(0);
            }

            int count;

            try
            {
                using (GifDecoder decoder = new GifDecoder(fileName))
                {
                    count = decoder.GetFrameCount();
                }
            }
            catch (Types.InvalidDataException)
            {
                count = 1;
            }

            return(count);
        }
Example #26
0
        /// <summary>
        /// 把Gif文件转成Png文件,放在directory目录下
        /// </summary>
        /// <param name="giffile">gif文件</param>
        /// <param name="directory">输出目录</param>
        /// <param name="type">输出类型</param>
        /// <returns></returns>
        public void GifToPngs(string giffile, string directory, string type)
        {
            if (type != "jpg" && type != "png" && type != "bmp")
            {
                var ex = new NullReferenceException();
                throw ex;
            }
            var gifDecoder = new GifDecoder();

            directory += "\\";
            if (!Directory.Exists(directory))
            {
                Directory.CreateDirectory(directory);
            }
            //读取
            gifDecoder.Read(giffile);
            for (int i = 0, count = gifDecoder.GetFrameCount(); i < count; i++)
            {
                Image frame = gifDecoder.GetFrame(i);  // frame i
                frame.Save(directory + "\\" + i.ToString("d3") + "." + type);
            }
            MessageBox.Show("gif解析完成");
        }
Example #27
0
        public void Bug2940669()
        {
            ReportStart();
            string folder = @"images\Bug2940669\";
            string bmpName;
            Image  expectedBitmap;
            Image  actualBitmap;

            foreach (string gifName in Directory.GetFiles(folder, "*.gif"))
            {
                _decoder = new GifDecoder(gifName);
                _decoder.Decode();
                for (int i = 0; i < _decoder.Frames.Count; i++)
                {
                    actualBitmap   = _decoder.Frames[i].TheImage;
                    bmpName        = gifName + ".frame " + i + ".bmp";
                    expectedBitmap = Bitmap.FromFile(bmpName);
                    ImageAssert.AreEqual(expectedBitmap, actualBitmap,
                                         gifName + " Frame " + i);
                }
            }
            ReportEnd();
        }
Example #28
0
        public static BRESNode FromGIF(string file)
        {
            string   s = Path.GetFileNameWithoutExtension(file);
            BRESNode b = new BRESNode()
            {
                _name = s
            };
            PAT0Node p = new PAT0Node()
            {
                _name = s
            };

            p.CreateEntry();

            PAT0TextureNode t = p.Children[0].Children[0] as PAT0TextureNode;

            GifDecoder d = new GifDecoder();

            d.Read(file);

            int f = d.GetFrameCount();

            using (TextureConverterDialog dlg = new TextureConverterDialog())
            {
                dlg.Source = (Bitmap)d.GetFrame(0);
                if (dlg.ShowDialog(null, b) == DialogResult.OK)
                {
                    for (int i = 1; i < f; i++)
                    {
                        dlg.Source = (Bitmap)d.GetFrame(i);
                        dlg.EncodeSource();
                    }
                }
            }

            return(b);
        }
Example #29
0
        public void Process()
        {
            GifRepeatBehavior gifRepeatBehavior = new GifRepeatBehavior();

            if (_iterationCount.IsInfinite)
            {
                gifRepeatBehavior.LoopForever = true;
            }
            else
            {
                gifRepeatBehavior.LoopForever = false;
                gifRepeatBehavior.Count       = (int)_iterationCount.Value;
            }

            _gifDecoder = new GifDecoder(_stream);
            var pixSize = new PixelSize(_gifDecoder.Header.Dimensions.Width, _gifDecoder.Header.Dimensions.Height);

            _targetBitmap                  = new WriteableBitmap(pixSize, new Vector(96, 96), PixelFormat.Bgra8888);
            _targerImage.Source            = _targetBitmap;
            _bgWorker                      = new GifBackgroundWorker(_gifDecoder, gifRepeatBehavior);
            _bgWorker.CurrentFrameChanged += FrameChanged;

            Run();
        }
Example #30
0
        public void ConsumeAnimatedGIFTest()
        {
            MemoryStream       ms      = new MemoryStream();
            AnimatedGifEncoder encoder = new AnimatedGifEncoder();

            // encoder.SetDelay(200);
            encoder.SetFrameRate(5);
            encoder.Start(ms);
            for (char i = 'a'; i <= 'z'; i++)
            {
                Console.Write(i.ToString());
                encoder.AddFrame(ThumbnailBitmap.GetBitmapFromText(i.ToString(), 48, 100, 200));
            }
            Console.WriteLine();
            encoder.Finish();
            ms.Flush();
            ms.Seek(0, SeekOrigin.Begin);

            GifDecoder decoder = new GifDecoder();

            decoder.Read(ms);
            Console.WriteLine("Frames: {0}", decoder.GetFrameCount());
            Assert.AreEqual(26, decoder.GetFrameCount());
        }
Example #31
0
        public void TestLoadGIF89a()
        {
            GifDecoder a_decoder = new GifDecoder();
            Stream     sm        = Assembly.GetExecutingAssembly().GetManifestResourceStream("SnCore.Tools.Tests.Images.animated.gif");

            Console.WriteLine("Bytes: {0}", sm.Length);
            a_decoder.Read(sm);
            Console.WriteLine("Frames: {0}", a_decoder.GetFrameCount());

            sm.Seek(0, SeekOrigin.Begin);
            Assert.IsNotNull(sm);
            ThumbnailBitmap b = new ThumbnailBitmap(sm);

            Console.WriteLine("Size: {0}x{1}", b.FullSize.Width, b.FullSize.Height);
            Assert.AreEqual(new Size(320, 240), b.FullSize);
            Assert.IsNotNull(b.Thumbnail);
            Assert.IsNotNull(b.Bitmap);
            ThumbnailBitmap th = new ThumbnailBitmap(b.Thumbnail);

            Console.WriteLine("Size: {0}x{1}", th.FullSize.Width, th.FullSize.Height);
            Assert.AreEqual(new Size(150, 100), th.FullSize);

            // make sure that the bitmap is still animated
            Console.WriteLine("Bytes: {0}", b.Bitmap.Length);
            GifDecoder decoder = new GifDecoder();

            decoder.Read(new MemoryStream(b.Bitmap));
            Console.WriteLine("Frames: {0}", decoder.GetFrameCount());

            GifDecoder th_decoder = new GifDecoder();

            Console.WriteLine("Bytes: {0}", b.Thumbnail.Length);
            th_decoder.Read(new MemoryStream(b.Thumbnail));
            Console.WriteLine("Frames: {0}", th_decoder.GetFrameCount());
            Assert.AreEqual(th_decoder.GetFrameCount(), decoder.GetFrameCount());
        }
        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();
        }
        public void Bug2940635()
        {
            ReportStart();
            string gifName
                = @"images\Bug2940635\Bug2940635TransparentColourIndexOutOfRangeException.gif";
            _decoder = new GifDecoder( gifName );
            _decoder.Decode();

            string bmpName;
            Image expectedBitmap;
            Image actualBitmap;
            for( int i = 0; i < _decoder.Frames.Count; i++ )
            {
                actualBitmap = _decoder.Frames[i].TheImage;
                bmpName = gifName + ".frame " + i + ".bmp";
                expectedBitmap = Bitmap.FromFile( bmpName );
                ImageAssert.AreEqual( expectedBitmap, actualBitmap, "Frame " + i );
            }
            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();
 }
        private void ConstructorStreamNullGraphicControlExtensionTest( bool xmlDebugging )
        {
            _decoder = new GifDecoder( @"images\NoGraphicControlExtension.gif",
                                       xmlDebugging );
            _decoder.Decode();
            Assert.AreEqual( ErrorState.NoGraphicControlExtension,
                             _decoder.Frames[0].ErrorState );
            Bitmap expected = new Bitmap( @"images\NoGraphicControlExtension.bmp" );
            Bitmap actual = (Bitmap) _decoder.Frames[0].TheImage;
            BitmapAssert.AreEqual( expected, actual );

            if( xmlDebugging )
            {
                Assert.AreEqual( ExpectedDebugXml, _decoder.Frames[0].DebugXml );
            }
        }
        private void ConstructorStreamUseLocalTest( bool xmlDebugging )
        {
            _decoder = new GifDecoder( @"images\wikipedia example UseLocal.gif",
                                       xmlDebugging );
            _decoder.Decode();
            _frame = _decoder.Frames[0];

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

            WikipediaExample.CheckImage( _frame.TheImage );

            // Check image descriptor
            ImageDescriptor id = _frame.ImageDescriptor;
            Assert.AreEqual( true, id.HasLocalColourTable,
                             "HasLocalColourTable" );
            Assert.AreEqual( false, id.IsInterlaced, "IsInterlaced" );
            Assert.AreEqual( false, id.IsSorted, "LocalColourTableIsSorted" );
            Assert.AreEqual( 4, id.LocalColourTableSize, "LocalColourTableSize" );
            Assert.AreEqual( new Point( 0, 0 ), id.Position, "Position" );
            Assert.AreEqual( new Size( 3, 5 ), id.Size, "Size" );

            WikipediaExample.CheckGraphicControlExtension( _frame.GraphicControlExtension );
            WikipediaExample.CheckImageData( _frame.IndexedPixels );
            Assert.AreEqual( 0, _frame.BackgroundColour.R );
            Assert.AreEqual( 0, _frame.BackgroundColour.G );
            Assert.AreEqual( 0, _frame.BackgroundColour.B );

            if( xmlDebugging )
            {
                Assert.AreEqual( ExpectedDebugXml, _frame.DebugXml );
            }
        }
Example #37
0
 public static AnimatedImage Load(Stream s)
 {
     GifDecoder g = new GifDecoder();
     return g.DecodeImage(s);
 }
        public void BadSignature()
        {
            ReportStart();

            string[] files = Directory.GetFiles( Directory.GetCurrentDirectory() );
            foreach( string file in files )
            {
                Stream s = File.Open( file, FileMode.Open );
                byte[] bytes = new byte[3];
                s.Read( bytes, 0, 3 );
                s.Close();

                StringBuilder sb = new StringBuilder();
                foreach( byte b in bytes )
                {
                    sb.Append( (char) b );
                }
                if( sb.ToString() != "GIF" )
                {
                    _decoder = new GifDecoder( file );
                    _decoder.Decode();
                    Assert.AreEqual( true,
                                     _decoder.TestState( ErrorState.BadSignature ),
                                     file + ": " + _decoder.ConsolidatedState );
                }
            }
            ReportEnd();
        }
        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();
        }
        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 ConstructorStreamNoColourTableTest()
 {
     ReportStart();
     _decoder = new GifDecoder( @"images\NoColourTable.gif" );
     _decoder.Decode();
     Assert.AreEqual( ErrorState.FrameHasNoColourTable, _decoder.ConsolidatedState );
     ReportEnd();
 }
        public void NullStream()
        {
            ReportStart();

            Stream stream = null;
            try
            {
                _decoder = new GifDecoder( stream );
            }
            catch( ArgumentNullException ex )
            {
                StringAssert.Contains( "inputStream", ex.Message );
                ReportEnd();
                throw;
            }
        }
 public void Bug2940669()
 {
     ReportStart();
     string folder = @"images\Bug2940669\";
     string bmpName;
     Image expectedBitmap;
     Image actualBitmap;
     foreach( string gifName in Directory.GetFiles( folder, "*.gif" ) )
     {
         _decoder = new GifDecoder( gifName );
         _decoder.Decode();
         for( int i = 0; i < _decoder.Frames.Count; i++ )
         {
             actualBitmap = _decoder.Frames[i].TheImage;
             bmpName = gifName + ".frame " + i + ".bmp";
             expectedBitmap = Bitmap.FromFile( bmpName );
             ImageAssert.AreEqual( expectedBitmap, actualBitmap,
                                   gifName + " Frame " + i );
         }
     }
     ReportEnd();
 }
        private void DecodeSmiley( bool xmlDebugging )
        {
            string fileName = @"images\smiley\smiley.gif";
            _decoder = new GifDecoder( fileName, xmlDebugging );
            _decoder.Decode();
            _lsd = _decoder.LogicalScreenDescriptor;
            int expectedColourTableSize = 128;

            Assert.AreEqual( "GIF", _decoder.Header.Signature );
            Assert.AreEqual( "89a", _decoder.Header.Version );
            Assert.IsNotNull( _decoder.GlobalColourTable );
            Assert.AreEqual( true, _lsd.HasGlobalColourTable );
            Assert.AreEqual( expectedColourTableSize,
                             _lsd.GlobalColourTableSize );
            Assert.AreEqual( expectedColourTableSize,
                                _decoder.GlobalColourTable.Length );
            Assert.AreEqual( 7, _lsd.ColourResolution );
            Assert.AreEqual( Color.FromArgb( 255, 0, 0, 255 ), _decoder.BackgroundColour );
            Assert.AreEqual( 0, _lsd.BackgroundColourIndex );
            Assert.AreEqual( false, _lsd.GlobalColourTableIsSorted );
            Assert.AreEqual( 18, _lsd.LogicalScreenSize.Width );
            Assert.AreEqual( 18, _lsd.LogicalScreenSize.Height );
            Assert.AreEqual( 0, _lsd.PixelAspectRatio );
            Assert.AreEqual( 0, _decoder.NetscapeExtension.LoopCount );
            Assert.AreEqual( ErrorState.Ok, _decoder.ConsolidatedState );
            Assert.AreEqual( 4, _decoder.Frames.Count );
            int frameNumber = 0;
            string frameId;
            foreach( GifFrame thisFrame in _decoder.Frames )
            {
                frameId = "Frame " + frameNumber;
                Assert.IsNull( thisFrame.LocalColourTable, frameId );

                #region image descriptor properties
                ImageDescriptor descriptor = thisFrame.ImageDescriptor;
                Assert.AreEqual( false, descriptor.HasLocalColourTable, frameId );
                Assert.AreEqual( expectedColourTableSize,
                                 descriptor.LocalColourTableSize,
                                 frameId );
                Assert.AreEqual( false, descriptor.IsInterlaced, frameId );
                Assert.AreEqual( false, descriptor.IsSorted, frameId );
                #endregion

                #region graphic control extension properties
                GraphicControlExtension gce = thisFrame.GraphicControlExtension;
                Assert.AreEqual( 4, gce.BlockSize, frameId );
                Assert.AreEqual( 0, gce.TransparentColourIndex, frameId );
                Assert.IsTrue( gce.HasTransparentColour, frameId );
                Assert.IsFalse( gce.ExpectsUserInput, frameId );
                #endregion

                switch( frameNumber )
                {
                    case 0:
                        Assert.AreEqual( 250, thisFrame.Delay, frameId );
                        Assert.AreEqual( 250, gce.DelayTime, frameId );
                        Assert.AreEqual( DisposalMethod.DoNotDispose,
                                         gce.DisposalMethod, frameId );
                        break;
                    case 1:
                        Assert.AreEqual( 5, thisFrame.Delay, frameId );
                        Assert.AreEqual( 5, gce.DelayTime, frameId );
                        Assert.AreEqual( DisposalMethod.RestoreToBackgroundColour,
                                         gce.DisposalMethod, frameId );
                        break;
                    case 2:
                        Assert.AreEqual( 10, thisFrame.Delay, frameId );
                        Assert.AreEqual( 10, gce.DelayTime, frameId );
                        Assert.AreEqual( DisposalMethod.RestoreToBackgroundColour,
                                         gce.DisposalMethod, frameId );
                        break;
                    case 3:
                        Assert.AreEqual( 5, thisFrame.Delay, frameId );
                        Assert.AreEqual( 5, gce.DelayTime, frameId );
                        Assert.AreEqual( DisposalMethod.DoNotDispose,
                                         gce.DisposalMethod, frameId );
                        break;
                }
                frameNumber++;
            }
            CompareFrames( fileName );

            if( xmlDebugging )
            {
                Assert.AreEqual( ExpectedDebugXml, _decoder.DebugXml );
            }
        }
        private void LookIn( string path )
        {
            _status = "Looking in " + path;
            string[] gifs;
            try
            {
                gifs = Directory.GetFiles( path, "*.gif" );
                foreach( string gif in gifs )
                {
                    _status = "Decoding " + gif;
                    try
                    {
                        GifDecoder decoder = new GifDecoder( gif );
                        decoder.Dispose();
                    }
                    catch( Exception )
                    {
                        WriteMessage( "Exception while decoding " + gif );
                        throw;
                    }
                }

                string[] folders = Directory.GetDirectories( path );
                foreach( string folder in folders )
                {
                    LookIn( folder );
                }
            }
            catch( UnauthorizedAccessException )
            {
                // suppress
            }
        }
        private void DecodeRotatingGlobe( bool xmlDebugging )
        {
            string fileName
                = @"images\globe\spinning globe better 200px transparent background.gif";
            _decoder = new GifDecoder( fileName, xmlDebugging );
            WriteMessage( "Started decoding. XmlDebugging=" + xmlDebugging );
            _decoder.Decode();
            WriteMessage( "Finished decoding. XmlDebugging=" + xmlDebugging );

            if( xmlDebugging )
            {
                Assert.AreEqual( ExpectedDebugXml, _decoder.DebugXml );
            }

            _lsd = _decoder.LogicalScreenDescriptor;
            int expectedColourTableSize = 64;

            Assert.AreEqual( ErrorState.Ok, _decoder.ConsolidatedState );
            Assert.AreEqual( "GIF", _decoder.Header.Signature );
            Assert.AreEqual( "89a", _decoder.Header.Version );
            Assert.IsNotNull( _decoder.GlobalColourTable );
            Assert.AreEqual( true, _lsd.HasGlobalColourTable );
            Assert.AreEqual( expectedColourTableSize,
                             _lsd.GlobalColourTableSize );
            Assert.AreEqual( expectedColourTableSize,
                                _decoder.GlobalColourTable.Length );
            Assert.AreEqual( 2, _lsd.ColourResolution );
            Assert.AreEqual( Color.FromArgb( 255, 255, 255, 255 ),
                             _decoder.BackgroundColour );
            Assert.AreEqual( 63, _lsd.BackgroundColourIndex );
            Assert.AreEqual( false, _lsd.GlobalColourTableIsSorted );
            Assert.AreEqual( 200, _lsd.LogicalScreenSize.Width );
            Assert.AreEqual( 191, _lsd.LogicalScreenSize.Height );
            Assert.AreEqual( 0, _lsd.PixelAspectRatio );
            Assert.AreEqual( 0, _decoder.NetscapeExtension.LoopCount );
            Assert.AreEqual( ErrorState.Ok, _decoder.ErrorState );
            Assert.AreEqual( 20, _decoder.Frames.Count );
            int frameNumber = 0;
            string frameId;
            foreach( GifFrame thisFrame in _decoder.Frames )
            {
                frameId = "Frame " + frameNumber;
                Assert.IsNull( thisFrame.LocalColourTable, frameId );
                Assert.AreEqual( 10, thisFrame.Delay, frameId );

                #region image descriptor tests
                ImageDescriptor descriptor = thisFrame.ImageDescriptor;
                Assert.AreEqual( false, descriptor.HasLocalColourTable, frameId );
                Assert.AreEqual( 2,
                                 descriptor.LocalColourTableSize,
                                 frameId );
                Assert.AreEqual( 200, descriptor.Size.Width, frameId );
                Assert.AreEqual( 191, descriptor.Size.Height, frameId );
                Assert.AreEqual( 0, descriptor.Position.X, frameId );
                Assert.AreEqual( 0, descriptor.Position.Y, frameId );
                Assert.AreEqual( false, descriptor.IsInterlaced, frameId );
                Assert.AreEqual( false, descriptor.IsSorted, frameId );
                #endregion

                #region graphic control extension tests
                GraphicControlExtension gce = thisFrame.GraphicControlExtension;
                Assert.AreEqual( 4, gce.BlockSize, frameId );
                Assert.AreEqual( 10, gce.DelayTime, frameId );
                if( frameNumber == 19 )
                {
                    Assert.AreEqual( DisposalMethod.DoNotDispose,
                                     gce.DisposalMethod, frameId );
                }
                else
                {
                    Assert.AreEqual( DisposalMethod.RestoreToBackgroundColour,
                                     gce.DisposalMethod, frameId );
                }
                Assert.AreEqual( 63, gce.TransparentColourIndex, frameId );
                Assert.IsTrue( gce.HasTransparentColour, frameId );
                Assert.IsFalse( gce.ExpectsUserInput, frameId );
                #endregion

                frameNumber++;
            }

            CompareFrames( fileName );
        }
        public void FileNotFound()
        {
            ReportStart();

            _decoder = new GifDecoder( "nonexist.gif" );
            // Don't try to catch the exception because it's thrown by the CLR
            // rather than by GifDecoder.
        }
        public void UnreadableStream()
        {
            ReportStart();

            // open a write-only stream
            Stream s = File.OpenWrite( "temp.temp" );
            try
            {
                _decoder = new GifDecoder( s );
            }
            catch( ArgumentException ex )
            {
                s.Close();
                string message
                    = "The supplied stream cannot be read";
                Assert.AreEqual( "inputStream", ex.ParamName );
                StringAssert.Contains( message, ex.Message );
                ReportEnd();
                throw;
            }
            finally
            {
                s.Close();
                File.Delete( "temp.temp" );
            }
        }
        /// <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" );
        }
 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 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 NullFileName()
        {
            ReportStart();

            string fileName = null;
            try
            {
                _decoder = new GifDecoder( fileName );
            }
            catch( ArgumentNullException ex )
            {
                StringAssert.Contains( "name", ex.Message );
                ReportEnd();
                throw;
            }
        }
 public void InterlaceTest()
 {
     ReportStart();
     _decoder = new GifDecoder( @"images\Interlaced.gif" );
     _decoder.Decode();
     Assert.AreEqual( true, _decoder.Frames[0].ImageDescriptor.IsInterlaced );
     Bitmap expected = new Bitmap( @"images\Interlaced.bmp" );
     Bitmap actual = (Bitmap) _decoder.Frames[0].TheImage;
     BitmapAssert.AreEqual( expected, actual );
     ReportEnd();
 }
 public void PositionDecodedFrameGetTest()
 {
     ReportStart();
     _decoder = new GifDecoder( @"images\smiley\smiley.gif" );
     _decoder.Decode();
     for( int i = 0; i < _decoder.Frames.Count; i++ )
     {
         _frame = _decoder.Frames[i];
         Assert.AreEqual( _frame.ImageDescriptor.Position,
                          _frame.Position,
                          "Frame " + i );
     }
     ReportEnd();
 }
 public void PositionDecodedFrameSetTest()
 {
     ReportStart();
     _decoder = new GifDecoder( @"images\smiley\smiley.gif" );
     _decoder.Decode();
     _frame = _decoder.Frames[0];
     try
     {
         _frame.Position = new Point( 1, 1 );
     }
     catch( InvalidOperationException ex )
     {
         string message
             = "This GifFrame was returned by a GifDecoder so this "
             + "property is read-only";
         StringAssert.Contains( message, ex.Message );
         ReportEnd();
         throw;
     }
 }
 public void LsdEndOfInputStream()
 {
     _decoder = new GifDecoder( GifFileName );
     _decoder.Decode();
     Assert.AreEqual( ErrorState.EndOfInputStream,
                      _decoder.ConsolidatedState );
 }
        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 ExpectsUserInputDecodedFrameGetTest()
 {
     ReportStart();
     _decoder = new GifDecoder( @"images\smiley\smiley.gif" );
     _decoder.Decode();
     for( int i = 0; i < _decoder.Frames.Count; i++ )
     {
         _frame = _decoder.Frames[i];
         Assert.AreEqual( _frame.GraphicControlExtension.ExpectsUserInput,
                          _frame.ExpectsUserInput,
                          "Frame " + i );
     }
     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();
        }