示例#1
0
        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();
        }
示例#2
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();
        }
示例#3
0
        static void Main(string[] args)
        {
            GifImage gifImage = GifDecoder.Decode(@"..\..\..\Examples\worldmap2.gif");

            ColorRGB[] globalPalette = ColorRGB.MakePalette(gifImage.GlobalColorTable);
            GifCube    cube          = new GifCube();
            byte       sliceT        = 0;

            foreach (GifFrame f in gifImage.Frames)
            {
                byte[]     colorTableBytes = f.LocalColorTable;
                ColorRGB[] palette;
                if (colorTableBytes == null)
                {
                    palette = globalPalette;
                }
                else
                {
                    palette = ColorRGB.MakePalette(colorTableBytes);
                }

                cube.AddFrame(sliceT, new GifCubeSlice(f.IndexedPixel, gifImage.Width, palette));
            }

            GifScriptState scriptState = new GifScriptState();

            scriptState.Init(cube);
            while (!scriptState.halted)
            {
                scriptState.Tick();
            }
        }
示例#4
0
 public void LsdEndOfInputStream()
 {
     _decoder = new GifDecoder(GifFileName);
     _decoder.Decode();
     Assert.AreEqual(ErrorState.EndOfInputStream,
                     _decoder.ConsolidatedState);
 }
示例#5
0
        /// <summary>
        /// 将Gif图片进行旋转或者翻转
        /// </summary>
        /// <param name="gifFilePath">原图像路径</param>
        /// <param name="rotateType">翻转或者旋转方式</param>
        /// <param name="outputPath">输出路径</param>
        public static void Rotate(string gifFilePath, RotateFlipType rotateType, string outputPath)
        {
            if (!File.Exists(gifFilePath))
            {
                throw new IOException(string.Format("文件{0}不存在!", gifFilePath));
            }
            using (Bitmap ora_Img = new Bitmap(gifFilePath))
            {
                if (ora_Img.RawFormat.Guid != ImageFormat.Gif.Guid)
                {
                    throw new IOException(string.Format("文件{0}!", gifFilePath));
                }
            }
            GifImage gifImage = GifDecoder.Decode(gifFilePath);

            ThinkDisposalMethod(gifImage);
            int index = 0;

            foreach (GifFrame f in gifImage.Frames)
            {
                f.Image.RotateFlip(rotateType);
                f.ImageDescriptor.Width  = (short)f.Image.Width;
                f.ImageDescriptor.Height = (short)f.Image.Height;
                if (index++ == 0)
                {
                    gifImage.LogicalScreenDescriptor.Width  = (short)f.Image.Width;
                    gifImage.LogicalScreenDescriptor.Height = (short)f.Image.Height;
                }
            }
            GifEncoder.Encode(gifImage, outputPath);
        }
示例#6
0
        /// <summary>
        /// 对gif动画添加水印
        /// </summary>
        /// <param name="gifFilePath">原gif动画的路径</param>
        /// <param name="text">水印文字</param>
        /// <param name="textForceColor">水印文字的颜色,因为gif不是真彩色图片,所以在显示的时候,该颜色可能有所误差,但基本上可以确定颜色范围</param>
        /// <param name="font">字体</param>
        /// <param name="x">水印位置横坐标</param>
        /// <param name="y">水印位置纵坐标</param>
        /// <param name="outputPath">输出路径</param>
        public static void SmartWaterMark(string gifFilePath, string text, Color textForceColor, Font font, float x, float y, string outputPath)
        {
            if (!File.Exists(gifFilePath))
            {
                throw new IOException(string.Format("文件{0}不存在!", gifFilePath));
            }
            using (Bitmap ora_Img = new Bitmap(gifFilePath))
            {
                if (ora_Img.RawFormat.Guid != ImageFormat.Gif.Guid)
                {
                    throw new IOException(string.Format("文件{0}!", gifFilePath));
                }
            }
            GifImage gifImage = GifDecoder.Decode(gifFilePath);

            ThinkDisposalMethod(gifImage);
            Color textColor = textForceColor;// Color.FromArgb(closestC);

            foreach (GifFrame f in gifImage.Frames)
            {
                Graphics g = Graphics.FromImage(f.Image);
                g.DrawString(text, font, new SolidBrush(textColor), new PointF(x, y));
                g.Dispose();
            }
            GifEncoder.Encode(gifImage, outputPath);
        }
示例#7
0
        private void init(Stream stream, GIFFrameUpdatedCallbackMethod frameUpdatedCallback)
        {
            // set gif frame update callback
            this.FrameUpdatedCallback = frameUpdatedCallback;

            // decode gif image
            var gifDecoder = new GifDecoder();
            var image      = new ExtendedImage();

            gifDecoder.Decode(image, stream);

            // add frames and load unity textures
            frames = new List <TextureGIFFrame>();
            var firstFrame = new TextureGIFFrame(createTexture(image.PixelWidth, image.PixelHeight, image.Pixels), TimeSpan.FromSeconds(image.DelayTime / 100d));

            frames.Add(firstFrame);
            var lastFrame = firstFrame;

            foreach (var frame in image.Frames)
            {
                var newFrame = new TextureGIFFrame(createTexture(frame.PixelWidth, frame.PixelHeight, frame.Pixels), TimeSpan.FromSeconds(frame.DelayTime / 100d));
                frames.Add(newFrame);
                if (lastFrame != null)
                {
                    lastFrame.nextFrame = newFrame;
                }
                lastFrame = newFrame;
            }

            // set starting image
            CurrentFrame        = frames[0];
            lastFrame.nextFrame = firstFrame;
        }
示例#8
0
        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);
            }
        }
示例#9
0
        /// <summary>
        /// 对Gif图片进行剪裁
        /// </summary>
        /// <param name="gifFilePath">原图像</param>
        /// <param name="rect">剪裁区域</param>
        /// <param name="outFilePath">输出路径</param>
        public static void Crop(string gifFilePath, Rectangle rect, string outFilePath)
        {
            if (!File.Exists(gifFilePath))
            {
                throw new IOException(string.Format("文件{0}不存在!", gifFilePath));
            }
            using (Bitmap ora_Img = new Bitmap(gifFilePath))
            {
                if (ora_Img.RawFormat.Guid != ImageFormat.Gif.Guid)
                {
                    throw new IOException(string.Format("文件{0}!", gifFilePath));
                }
            }
            GifImage gifImage = GifDecoder.Decode(gifFilePath);

            ThinkDisposalMethod(gifImage);
            int index = 0;

            foreach (GifFrame f in gifImage.Frames)
            {
                f.Image = f.Image.Clone(rect, f.Image.PixelFormat);
                f.ImageDescriptor.Width  = (short)rect.Width;
                f.ImageDescriptor.Height = (short)rect.Height;
                if (index++ == 0)
                {
                    gifImage.LogicalScreenDescriptor.Width  = (short)rect.Width;
                    gifImage.LogicalScreenDescriptor.Height = (short)rect.Height;
                }
            }
            GifEncoder.Encode(gifImage, outFilePath);
        }
示例#10
0
 public void ConstructorStreamNoColourTableTest()
 {
     ReportStart();
     _decoder = new GifDecoder(@"images\NoColourTable.gif");
     _decoder.Decode();
     Assert.AreEqual(ErrorState.FrameHasNoColourTable, _decoder.ConsolidatedState);
     ReportEnd();
 }
示例#11
0
        public static Image FromFile(string filename)
        {
            //TODO: review here
            //should not depend on the extension
            string fileext = IO.Path.GetExtension(filename).ToLower();

            switch (fileext)
            {
            default:
                throw new NotSupportedException();

            case ".jpg":
            {
                JpegDecoder jpegDec = new JpegDecoder();
                ImageTools.ExtendedImage outputImg = new ImageTools.ExtendedImage();
                using (System.IO.FileStream fs = new IO.FileStream(filename, IO.FileMode.Open))
                {
                    jpegDec.Decode(outputImg, fs);
                }
                //return bitmap
                return(new Bitmap(outputImg.PixelWidth, outputImg.PixelHeight, outputImg.Pixels,
                                  outputImg.DensityXInt32, outputImg.DensityYInt32));
            }

            case ".gif":
            {
                GifDecoder gifDec = new GifDecoder();
                ImageTools.ExtendedImage outputImg = new ImageTools.ExtendedImage();
                using (System.IO.FileStream fs = new IO.FileStream(filename, IO.FileMode.Open))
                {
                    gifDec.Decode(outputImg, fs);
                }
                //return bitmap
                return(new Bitmap(outputImg.PixelWidth, outputImg.PixelHeight, outputImg.Pixels,
                                  outputImg.DensityXInt32, outputImg.DensityYInt32));
            }

            case ".png":
            {
                ImageTools.IO.Png.PngDecoder pngDecoder = new PngDecoder();
                //HjgPngDecoder pngDecoder = new HjgPngDecoder();
                //PngDecoder pngDecoder = new PngDecoder();
                ImageTools.ExtendedImage outputImg = new ImageTools.ExtendedImage();
                using (System.IO.FileStream fs = new IO.FileStream(filename, IO.FileMode.Open))
                {
                    pngDecoder.Decode(outputImg, fs);
                }

                Bitmap bmp = new Bitmap(outputImg.PixelWidth,
                                        outputImg.PixelHeight, outputImg.Pixels,
                                        outputImg.DensityXInt32, outputImg.DensityYInt32);
                bmp.PixelFormat = Imaging.PixelFormat.Format32bppArgb;
                return(bmp);
            }
            }
            return(null);
        }
示例#12
0
 public GifTexture(byte[] buffer)
 {
     gif = GifDecoder.Decode(buffer);
     if (gif == null)
     {
         throw new System.Exception("Could not decode gif");
     }
     SetFirstFrame();
 }
示例#13
0
 public GifTexture(string filename)
 {
     gif = GifDecoder.Decode(filename);
     if (gif == null)
     {
         throw new System.Exception("Could not decode gif");
     }
     SetFirstFrame();
 }
示例#14
0
        public static Image <Rgba32> ReadGif(Stream stream)
        {
            var decoder = new GifDecoder
            {
                DecodingMode = FrameDecodingMode.All
            };
            var gif = decoder.Decode <Rgba32>(new Configuration(), stream);

            stream.Dispose();
            return(gif);
        }
示例#15
0
        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();
        }
示例#16
0
 private void LoadGif()
 {
     try
     {
         _decoder.Decode();
         Invoke(new MethodInvoker(StopTheClock));
     }
     catch (Exception ex)
     {
         HandleException(ex);
     }
 }
示例#17
0
        public void Decode_VerifyRepeatCount(string imagePath, uint repeatCount)
        {
            var testFile = TestFile.Create(imagePath);

            using (var stream = new MemoryStream(testFile.Bytes, false))
            {
                var decoder = new GifDecoder();
                using (Image <Rgba32> image = decoder.Decode <Rgba32>(Configuration.Default, stream))
                {
                    GifMetadata meta = image.Metadata.GetGifMetadata();
                    Assert.Equal(repeatCount, meta.RepeatCount);
                }
            }
        }
示例#18
0
 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();
 }
示例#19
0
 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();
 }
示例#20
0
        public void Decode_VerifyRatio(string imagePath, int xResolution, int yResolution, PixelResolutionUnit resolutionUnit)
        {
            var testFile = TestFile.Create(imagePath);

            using (var stream = new MemoryStream(testFile.Bytes, false))
            {
                var decoder = new GifDecoder();
                using (Image <Rgba32> image = decoder.Decode <Rgba32>(Configuration.Default, stream))
                {
                    ImageMetaData meta = image.MetaData;
                    Assert.Equal(xResolution, meta.HorizontalResolution);
                    Assert.Equal(yResolution, meta.VerticalResolution);
                    Assert.Equal(resolutionUnit, meta.ResolutionUnits);
                }
            }
        }
示例#21
0
        /// <summary>
        /// 获取gif动画的缩略图
        /// </summary>
        /// <param name="gifFilePath">原gif图片路径</param>
        /// <param name="rate">缩放大小</param>
        /// <param name="outputPath">缩略图大小</param>
        public static void GetThumbnail(string gifFilePath, double rate, string outputPath)
        {
            if (!File.Exists(gifFilePath))
            {
                throw new IOException(string.Format("文件{0}不存在!", gifFilePath));
            }
            using (Bitmap ora_Img = new Bitmap(gifFilePath))
            {
                if (ora_Img.RawFormat.Guid != ImageFormat.Gif.Guid)
                {
                    throw new IOException(string.Format("文件{0}!", gifFilePath));
                }
            }
            GifImage gifImage = GifDecoder.Decode(gifFilePath);

            if (rate != 1.0)
            {
                gifImage.LogicalScreenDescriptor.Width  = (short)(gifImage.LogicalScreenDescriptor.Width * rate);
                gifImage.LogicalScreenDescriptor.Height = (short)(gifImage.LogicalScreenDescriptor.Height * rate);
                int index = 0;
                foreach (GifFrame f in gifImage.Frames)
                {
                    f.ImageDescriptor.XOffSet = (short)(f.ImageDescriptor.XOffSet * rate);
                    f.ImageDescriptor.YOffSet = (short)(f.ImageDescriptor.YOffSet * rate);
                    f.ImageDescriptor.Width   = (short)(f.ImageDescriptor.Width * rate);
                    f.ImageDescriptor.Height  = (short)(f.ImageDescriptor.Height * rate);
                    if (f.ImageDescriptor.Width == 0)
                    {
                        f.ImageDescriptor.Width = 1;
                    }
                    if (f.ImageDescriptor.Height == 0)
                    {
                        f.ImageDescriptor.Height = 1;
                    }
                    Bitmap   bmp = new Bitmap(f.ImageDescriptor.Width, f.ImageDescriptor.Height);
                    Graphics g   = Graphics.FromImage(bmp);
                    g.DrawImage(f.Image, new Rectangle(0, 0, f.ImageDescriptor.Width, f.ImageDescriptor.Height));
                    g.Dispose();
                    Quantizer(bmp, f.Palette);
                    f.Image.Dispose();
                    f.Image = bmp;
                    index++;
                }
                GifEncoder.Encode(gifImage, outputPath);
            }
        }
示例#22
0
        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);
            }
        }
示例#23
0
        /// <summary>
        /// 对gif动画添加图片水印
        /// </summary>
        /// <param name="gifFilePath">原图片路径</param>
        /// <param name="waterImg">水印图片</param>
        /// <param name="x">横坐标</param>
        /// <param name="y">纵坐标</param>
        /// <param name="outputPath">输出路径</param>
        public static void WaterMark(string gifFilePath, Bitmap waterImg, float x, float y, string outputPath)
        {
            if (!File.Exists(gifFilePath))
            {
                throw new IOException(string.Format("文件{0}不存在!", gifFilePath));
            }
            using (Bitmap ora_Img = new Bitmap(gifFilePath))
            {
                if (ora_Img.RawFormat.Guid != ImageFormat.Gif.Guid)
                {
                    throw new IOException(string.Format("文件{0}!", gifFilePath));
                }
            }
            GifImage gifImage = GifDecoder.Decode(gifFilePath);

            ThinkDisposalMethod(gifImage);
            foreach (GifFrame f in gifImage.Frames)
            {
                Graphics g = Graphics.FromImage(f.Image);
                g.DrawImage(waterImg, new PointF(x, y));
                g.Dispose();
                OcTreeQuantizer q          = new OcTreeQuantizer(8);
                Color32[]       cs         = q.Quantizer(f.Image);
                byte[]          lct        = new byte[cs.Length * 3];
                int             index      = 0;
                int             colorCount = 0;
                foreach (Color32 c in cs)
                {
                    lct[index++] = c.Red;
                    lct[index++] = c.Green;
                    lct[index++] = c.Blue;
                    if (c.ARGB == f.BgColor.ARGB)
                    {
                        f.GraphicExtension.TranIndex = (byte)colorCount;
                    }
                    colorCount++;
                }
                Quantizer(f.Image, cs);
                f.LocalColorTable         = lct;
                f.ImageDescriptor.LctFlag = true;
                f.ImageDescriptor.LctSize = 256;
                f.ColorDepth = 8;
            }
            GifEncoder.Encode(gifImage, outputPath);
        }
示例#24
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();
        }
示例#25
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);
        }
示例#26
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));
                }
            });
        }
示例#27
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));
                    }
                }
            }
        }
示例#28
0
        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]);
                    }
                }
        }
示例#29
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;
     }
 }
示例#30
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();
        }
        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 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 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 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();
 }
        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 );
            }
        }
 public void LsdEndOfInputStream()
 {
     _decoder = new GifDecoder( GifFileName );
     _decoder.Decode();
     Assert.AreEqual( ErrorState.EndOfInputStream,
                      _decoder.ConsolidatedState );
 }
 public void ConstructorStreamNoColourTableTest()
 {
     ReportStart();
     _decoder = new GifDecoder( @"images\NoColourTable.gif" );
     _decoder.Decode();
     Assert.AreEqual( ErrorState.FrameHasNoColourTable, _decoder.ConsolidatedState );
     ReportEnd();
 }
 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();
 }
 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 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 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 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();
        }
        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 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 );
        }
        /// <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 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 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 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 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 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();
 }
        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 );
            }
        }