示例#1
0
		public GifFrame( Stream inputStream,
		                 LogicalScreenDescriptor lsd,
		                 ColourTable gct,
		                 GraphicControlExtension gce,
		                 GifFrame previousFrame,
		                 GifFrame previousFrameBut1 )
			: base( inputStream, lsd, gct, gce, previousFrame, previousFrameBut1 )
		{}
示例#2
0
 public GifFrame(Stream inputStream,
                 LogicalScreenDescriptor lsd,
                 ColourTable gct,
                 GraphicControlExtension gce,
                 GifFrame previousFrame,
                 GifFrame previousFrameBut1)
     : this(inputStream, lsd, gct, gce, previousFrame, previousFrameBut1, false)
 {
 }
示例#3
0
		/// <summary>
		/// Sets the pixels of the decoded image.
		/// </summary>
		/// <param name="imageData">
		/// Table based image data containing the indices within the active
		/// colour table of the colours of the pixels in this frame.
		/// </param>
		/// <param name="lsd">
		/// The logical screen descriptor for the GIF stream.
		/// </param>
		/// <param name="id">
		/// The image descriptor for this frame.
		/// </param>
		/// <param name="activeColourTable">
		/// The colour table to use with this frame - either the global colour
		/// table or a local colour table.
		/// </param>
		/// <param name="gce">
		/// The graphic control extension, if any, which precedes this image in
		/// the input stream.
		/// </param>
		/// <param name="previousFrame">
		/// The frame which precedes this one in the GIF stream, if present.
		/// </param>
		/// <param name="previousFrameBut1">
		/// The frame which precedes the frame before this one in the GIF stream,
		/// if present.
		/// </param>
		/// <param name="status">
		/// GifComponentStatus containing any errors which occurred during the
		/// creation of the bitmap.
		/// </param>
		private static Bitmap CreateBitmap( TableBasedImageData imageData,
		                                    LogicalScreenDescriptor lsd,
		                                    ImageDescriptor id,
		                                    ColourTable activeColourTable,
		                                    GraphicControlExtension gce,
		                                    GifFrame previousFrame,
		                                    GifFrame previousFrameBut1, 
		                                    out GifComponentStatus status )
		{
			status = new GifComponentStatus( ErrorState.Ok, "" );
			Color[] pixelsForThisFrame = new Color[lsd.LogicalScreenSize.Width 
			                                       * lsd.LogicalScreenSize.Height];
			
			Bitmap baseImage = GetBaseImage( previousFrame, 
			                                 previousFrameBut1, 
			                                 lsd, 
			                                 gce, 
			                                 activeColourTable );

			// copy each source line to the appropriate place in the destination
			int pass = 1;
			int interlaceRowIncrement = 8;
			int interlaceRowNumber = 0; // the row of pixels we're currently 
										// setting in an interlaced image.
			for( int i = 0; i < id.Size.Height; i++)  
			{
				int pixelRowNumber = i;
				if( id.IsInterlaced ) 
				{
					#region work out the pixel row we're setting for an interlaced image
					if( interlaceRowNumber >= id.Size.Height ) 
					{
						pass++;
						switch( pass )
						{
							case 2 :
								interlaceRowNumber = 4;
								break;
							case 3 :
								interlaceRowNumber = 2;
								interlaceRowIncrement = 4;
								break;
							case 4 :
								interlaceRowNumber = 1;
								interlaceRowIncrement = 2;
								break;
						}
					}
					#endregion
					pixelRowNumber = interlaceRowNumber;
					interlaceRowNumber += interlaceRowIncrement;
				}
				
				// Colour in the pixels for this row
				pixelRowNumber += id.Position.Y;
				if( pixelRowNumber < lsd.LogicalScreenSize.Height ) 
				{
					int k = pixelRowNumber * lsd.LogicalScreenSize.Width;
					int dx = k + id.Position.X; // start of line in dest
					int dlim = dx + id.Size.Width; // end of dest line
					if( (k + lsd.LogicalScreenSize.Width) < dlim ) 
					{
						// TESTME: CreateBitmap - past dest edge
						dlim = k + lsd.LogicalScreenSize.Width; // past dest edge
					}
					int sx = i * id.Size.Width; // start of line in source
					while (dx < dlim) 
					{
						// map color and insert in destination
						int indexInColourTable = (int) imageData.Pixels[sx++];
						// Set this pixel's colour if its index isn't the 
						// transparent colour index, or if this frame doesn't
						// have a transparent colour.
						Color c;
						if( gce.HasTransparentColour && indexInColourTable == gce.TransparentColourIndex )
						{
							c = Color.Empty; // transparent pixel
						}
						else
						{
							if( indexInColourTable < activeColourTable.Length )
							{
								c = activeColourTable[indexInColourTable];
							}
							else
							{
								// TESTME: CreateBitmap - BadColourIndex
								c = Color.Black;
								string message 
									= "Colour index: "
									+ indexInColourTable
									+ ", colour table length: "
									+ activeColourTable.Length
									+ " (" + dx + "," + pixelRowNumber + ")";
								status = new GifComponentStatus( ErrorState.BadColourIndex, 
								                                 message );
							}
						}
						pixelsForThisFrame[dx] = c;
						dx++;
					}
				}
			}
			return CreateBitmap( baseImage, pixelsForThisFrame );
		}
示例#4
0
		public GifFrame( Stream inputStream,
		                 LogicalScreenDescriptor lsd,
		                 ColourTable gct,
		                 GraphicControlExtension gce,
		                 GifFrame previousFrame,
		                 GifFrame previousFrameBut1, 
		                 bool xmlDebugging )
			: base( xmlDebugging )
		{
			#region guard against null arguments
			if( lsd == null )
			{
				throw new ArgumentNullException( "lsd" );
			}
			
			if( gce == null )
			{
				SetStatus( ErrorState.NoGraphicControlExtension, "" );
				// use a default GCE
				gce = new GraphicControlExtension( GraphicControlExtension.ExpectedBlockSize, 
				                                   DisposalMethod.NotSpecified, 
				                                   false, 
				                                   false, 
				                                   100, 
				                                   0 );
			}
			#endregion
			
			int transparentColourIndex = gce.TransparentColourIndex;

			ImageDescriptor imageDescriptor = new ImageDescriptor( inputStream, 
			                                                       XmlDebugging );
			WriteDebugXmlNode( imageDescriptor.DebugXmlReader );
			
			#region determine the colour table to use for this frame
			Color backgroundColour = Color.FromArgb( 0 ); // TODO: is this the right background colour?
			// TODO: use backgroundColourIndex from the logical screen descriptor?
			ColourTable activeColourTable;
			if( imageDescriptor.HasLocalColourTable ) 
			{
				_localColourTable 
					= new ColourTable( inputStream,
					                   imageDescriptor.LocalColourTableSize, 
					                   XmlDebugging );
				WriteDebugXmlNode( _localColourTable.DebugXmlReader );
				activeColourTable = _localColourTable; // make local table active
			} 
			else 
			{
				if( gct == null )
				{
					// We have neither local nor global colour table, so we
					// won't be able to decode this frame.
					Bitmap emptyBitmap = new Bitmap( lsd.LogicalScreenSize.Width, 
					                                 lsd.LogicalScreenSize.Height );
					_image = emptyBitmap;
					_delay = gce.DelayTime;
					SetStatus( ErrorState.FrameHasNoColourTable, "" );
					return;
				}
				activeColourTable = gct; // make global table active
				if( lsd.BackgroundColourIndex == transparentColourIndex )
				{
					backgroundColour = Color.FromArgb( 0 );
				}
			}
			#endregion

			// decode pixel data
			int pixelCount = imageDescriptor.Size.Width * imageDescriptor.Size.Height;
			TableBasedImageData indexedPixels 
				= new TableBasedImageData( inputStream, pixelCount, XmlDebugging );
			WriteDebugXmlNode( indexedPixels.DebugXmlReader );
			
			if( indexedPixels.Pixels.Count == 0 )
			{
				// TESTME: constructor - indexedPixels.Pixels.Count == 0
				Bitmap emptyBitmap = new Bitmap( lsd.LogicalScreenSize.Width, 
				                                 lsd.LogicalScreenSize.Height );
				_image = emptyBitmap;
				_delay = gce.DelayTime;
				SetStatus( ErrorState.FrameHasNoImageData, "" );
				WriteDebugXmlFinish();
				return;
			}
			
			// Skip any remaining blocks up to the next block terminator (in
			// case there is any surplus data before the next frame)
			SkipBlocks( inputStream );

			_indexedPixels = indexedPixels;

			_extension = gce;
			if( gce != null )
			{
				_delay = gce.DelayTime;
			}
			_imageDescriptor = imageDescriptor;
			_backgroundColour = backgroundColour;
			GifComponentStatus status;
			_image = CreateBitmap( indexedPixels, 
			                       lsd,
			                       imageDescriptor,
			                       activeColourTable,
			                       gce,
			                       previousFrame,
			                       previousFrameBut1,
			                       out status );
			
			WriteDebugXmlFinish();
		}
示例#5
0
        /// <summary>
        /// Main file parser. Reads GIF content blocks.
        /// </summary>
        /// <param name="inputStream">
        /// Input stream from which the GIF data is to be read.
        /// </param>
        private void ReadContents( Stream inputStream )
        {
            // read GIF file content blocks
            bool done = false;
            GraphicControlExtension lastGce = null;
            string message; // for error conditions
            while( !done && ConsolidatedState == ErrorState.Ok )
            {
                int code = Read( inputStream );
                MyProgressCounters[_readStreamCounterText].Value
                    = (int) inputStream.Position;
                WriteCodeToDebugXml( code );

                switch( code )
                {

                    case CodeImageSeparator:
                        WriteDebugXmlComment( "0x2C - image separator" );
                        AddFrame( inputStream, lastGce );
                        MyProgressCounters[_readStreamCounterText].Value
                            = (int) inputStream.Position;
                        break;

                    case CodeExtensionIntroducer:
                        WriteDebugXmlComment( "0x21 - extension introducer" );
                        code = Read( inputStream );
                        MyProgressCounters[_readStreamCounterText].Value
                            = (int) inputStream.Position;
                        WriteCodeToDebugXml( code );
                        switch( code )
                        {
                            case CodePlaintextLabel:
                                // FEATURE: handle plain text extension
                                WriteDebugXmlComment( "0x01 - plain text extension" );
                                SkipBlocks( inputStream );
                                MyProgressCounters[_readStreamCounterText].Value
                                    = (int) inputStream.Position;
                                break;

                            case CodeGraphicControlLabel:
                                WriteDebugXmlComment( "0xF9 - graphic control label" );
                                lastGce = new GraphicControlExtension( inputStream,
                                                                       XmlDebugging );
                                MyProgressCounters[_readStreamCounterText].Value
                                    = (int) inputStream.Position;
                                WriteDebugXmlNode( lastGce.DebugXmlReader );
                                break;

                            case CodeCommentLabel:
                                // FEATURE: handle comment extension
                                WriteDebugXmlComment( "0xFE - comment extension" );
                                SkipBlocks( inputStream );
                                MyProgressCounters[_readStreamCounterText].Value
                                    = (int) inputStream.Position;
                                break;

                            case CodeApplicationExtensionLabel:
                                WriteDebugXmlComment( "0xFF - application extension label" );
                                ApplicationExtension ext
                                    = new ApplicationExtension( inputStream,
                                                                XmlDebugging );
                                MyProgressCounters[_readStreamCounterText].Value
                                    = (int) inputStream.Position;
                                WriteDebugXmlNode( ext.DebugXmlReader );
                                if( ext.ApplicationIdentifier == "NETSCAPE"
                                    && ext.ApplicationAuthenticationCode == "2.0" )
                                {
                                    _netscapeExtension = new NetscapeExtension( ext );
                                }
                                else
                                {
                                    // TESTME: ReadContents - non-Netscape application extension
                                    _applicationExtensions.Add( ext );
                                }
                                break;

                            default : // uninteresting extension
                                // TESTME: ReadContents - uninteresting extension
                                WriteDebugXmlComment( "Ignoring this extension" );
                                SkipBlocks( inputStream );
                                MyProgressCounters[_readStreamCounterText].Value
                                    = (int) inputStream.Position;
                                break;
                        }
                        break;

                    case CodeTrailer:
                        // We've reached an explicit end-of-data marker, so stop
                        // processing the stream.
                        WriteDebugXmlComment( "0x3B - end of data" );
                        done = true;
                        break;

                    case 0x00 : // bad byte, but keep going and see what happens
                        WriteDebugXmlComment( "0x00 - unexpected code" );
                        message
                            = "Unexpected block terminator encountered at "
                            + "position " + inputStream.Position
                            + " after reading " + _frames.Count + " frames.";
                        SetStatus( ErrorState.UnexpectedBlockTerminator,
                                   message );
                        break;

                    case -1: // reached the end of the input stream
                        WriteDebugXmlComment( "-1 - end of input stream" );
                        message
                            = "Reached the end of the input stream without "
                            + "encountering trailer 0x3b";
                        SetStatus( ErrorState.EndOfInputStream, message );
                        break;

                    default :
                        WriteDebugXmlComment( "Not a recognised code" );
                        message
                            = "Bad data block introducer: 0x"
                            + code.ToString( "X", CultureInfo.InvariantCulture ).PadLeft( 2, '0' )
                            + " (" + code + ") at position " + inputStream.Position
                            + " ("
                            + inputStream.Position.ToString( "X",
                                                           CultureInfo.InvariantCulture )
                            + " hex) after reading "
                            + _frames.Count + " frames.";
                        SetStatus( ErrorState.BadDataBlockIntroducer, message );
                        break;
                }
            }
        }
示例#6
0
        /// <summary>
        /// Reads a frame from the input stream and adds it to the collection
        /// of frames.
        /// </summary>
        /// <param name="inputStream">
        /// Input stream from which the frame is to be read.
        /// </param>
        /// <param name="lastGce">
        /// The graphic control extension most recently read from the input
        /// stream.
        /// </param>
        private void AddFrame( Stream inputStream,
		                       GraphicControlExtension lastGce )
        {
            GifFrame previousFrame;
            GifFrame previousFrameBut1;
            if( _frames.Count > 0 )
            {
                previousFrame = _frames[_frames.Count - 1];
            }
            else
            {
                previousFrame = null;
            }
            if( _frames.Count > 1 )
            {
                previousFrameBut1 = _frames[_frames.Count - 2];
            }
            else
            {
                previousFrameBut1 = null;
            }
            GifFrame frame = new GifFrame( inputStream,
                                           _lsd,
                                           _gct,
                                           lastGce,
                                           previousFrame,
                                           previousFrameBut1,
                                           XmlDebugging );
            MyProgressCounters[_readStreamCounterText].Value
                = (int) inputStream.Position;
            _frames.Add( frame );
            WriteDebugXmlNode( frame.DebugXmlReader );
        }
 private static void CheckGraphicControlExtension( Stream s, 
     Color transparentColour)
 {
     // check graphic control extension
     GraphicControlExtension gce = new GraphicControlExtension( s );
     Assert.AreEqual( ErrorState.Ok, gce.ConsolidatedState );
     Assert.AreEqual( 10, gce.DelayTime );
     if( transparentColour == Color.Empty )
     {
         Assert.AreEqual( 0, gce.TransparentColourIndex );
         Assert.AreEqual( false, gce.HasTransparentColour );
         Assert.AreEqual( DisposalMethod.DoNotDispose, gce.DisposalMethod );
     }
     else
     {
         Assert.AreEqual( true, gce.HasTransparentColour );
         // TODO: a way to check the transparent colour index?
         Assert.AreEqual( DisposalMethod.RestoreToBackgroundColour,
                          gce.DisposalMethod );
     }
     Assert.AreEqual( false, gce.ExpectsUserInput );
 }
        public void WriteToStreamTest()
        {
            ReportStart();
            int blockSize = 4;
            DisposalMethod disposalMethod = DisposalMethod.DoNotDispose;
            bool expectsUserInput = false;
            bool hasTransparentColour = true;
            int delayTime = 10;
            int transparentColourIndex = 6;
            _gce = new GraphicControlExtension( blockSize,
                                                disposalMethod,
                                                expectsUserInput,
                                                hasTransparentColour,
                                                delayTime,
                                                transparentColourIndex );

            MemoryStream s = new MemoryStream();
            _gce.WriteToStream( s );
            s.Seek( 0, SeekOrigin.Begin );

            _gce = new GraphicControlExtension( s );

            Assert.AreEqual( ErrorState.Ok, _gce.ConsolidatedState );
            Assert.AreEqual( blockSize, _gce.BlockSize );
            Assert.AreEqual( disposalMethod, _gce.DisposalMethod );
            Assert.AreEqual( expectsUserInput, _gce.ExpectsUserInput );
            Assert.AreEqual( hasTransparentColour, _gce.HasTransparentColour );
            Assert.AreEqual( delayTime, _gce.DelayTime );
            Assert.AreEqual( transparentColourIndex, _gce.TransparentColourIndex );

            ReportEnd();
        }
示例#9
0
        /// <summary>
        /// Gets the base image for this frame. This will be overpainted with
        /// the pixels for this frame, where they are not transparent.
        /// </summary>
        /// <param name="previousFrame">
        /// The frame which preceded this frame in the GIF stream.
        /// Null if this is the first frame in the stream.
        /// </param>
        /// <param name="previousFrameBut1">
        /// The frame which preceded the previous frame in the GIF stream.
        /// Null if this is the first or seond frame in the stream.
        /// </param>
        /// <param name="lsd">
        /// The logical screen descriptor for this GIF stream.
        /// </param>
        /// <param name="gce">
        /// The graphic control extension for this frame.
        /// </param>
        /// <param name="act">
        /// The active colour table for this frame.
        /// </param>
        /// <returns></returns>
        private static Bitmap GetBaseImage(GifFrame previousFrame,
                                           GifFrame previousFrameBut1,
                                           LogicalScreenDescriptor lsd,
                                           GraphicControlExtension gce,
                                           ColourTable act)
        {
            #region Get the disposal method of the previous frame read from the GIF stream
            DisposalMethod previousDisposalMethod;
            if (previousFrame == null)
            {
                previousDisposalMethod = DisposalMethod.NotSpecified;
            }
            else
            {
                previousDisposalMethod = previousFrame.GraphicControlExtension.DisposalMethod;
            }
            #endregion

            Bitmap baseImage;
            int    width  = lsd.LogicalScreenSize.Width;
            int    height = lsd.LogicalScreenSize.Height;

            #region paint baseImage
            switch (previousDisposalMethod)
            {
            case DisposalMethod.DoNotDispose:
                // pre-populate image with previous frame
                baseImage = new Bitmap(previousFrame.TheImage);
                break;

            case DisposalMethod.RestoreToBackgroundColour:
                // pre-populate image with background colour
                Color backgroundColour;
                if (lsd.BackgroundColourIndex == gce.TransparentColourIndex)
                {
                    backgroundColour = Color.Empty;
                }
                else
                {
                    // TESTME: background colour index different to transparent colour
                    backgroundColour = act[lsd.BackgroundColourIndex];
                }
                baseImage = new Bitmap(width, height);
                for (int y = 0; y < height; y++)
                {
                    for (int x = 0; x < height; x++)
                    {
                        baseImage.SetPixel(x, y, backgroundColour);
                    }
                }
                break;

            case DisposalMethod.RestoreToPrevious:
                // pre-populate image with previous frame but 1
                // TESTME: DisposalMethod.RestoreToPrevious
                baseImage = new Bitmap(previousFrameBut1.TheImage);
                break;

            default:                     // DisposalMethod.NotSpecified
                if (previousFrame == null)
                {
                    // this is the first frame so start with an empty bitmap
                    baseImage = new Bitmap(width, height);
                }
                else
                {
                    // pre-populate image with previous frame
                    // TESTME: DisposalMethod.NotSpecified on 2nd frame or later
                    baseImage = new Bitmap(previousFrame.TheImage);
                }
                break;
            }
            #endregion

            return(baseImage);
        }
示例#10
0
        /// <summary>
        /// Sets the pixels of the decoded image.
        /// </summary>
        /// <param name="imageData">
        /// Table based image data containing the indices within the active
        /// colour table of the colours of the pixels in this frame.
        /// </param>
        /// <param name="lsd">
        /// The logical screen descriptor for the GIF stream.
        /// </param>
        /// <param name="id">
        /// The image descriptor for this frame.
        /// </param>
        /// <param name="activeColourTable">
        /// The colour table to use with this frame - either the global colour
        /// table or a local colour table.
        /// </param>
        /// <param name="gce">
        /// The graphic control extension, if any, which precedes this image in
        /// the input stream.
        /// </param>
        /// <param name="previousFrame">
        /// The frame which precedes this one in the GIF stream, if present.
        /// </param>
        /// <param name="previousFrameBut1">
        /// The frame which precedes the frame before this one in the GIF stream,
        /// if present.
        /// </param>
        /// <param name="status">
        /// GifComponentStatus containing any errors which occurred during the
        /// creation of the bitmap.
        /// </param>
        private static Bitmap CreateBitmap(TableBasedImageData imageData,
                                           LogicalScreenDescriptor lsd,
                                           ImageDescriptor id,
                                           ColourTable activeColourTable,
                                           GraphicControlExtension gce,
                                           GifFrame previousFrame,
                                           GifFrame previousFrameBut1,
                                           out GifComponentStatus status)
        {
            status = new GifComponentStatus(ErrorState.Ok, "");
            Color[] pixelsForThisFrame = new Color[lsd.LogicalScreenSize.Width
                                                   * lsd.LogicalScreenSize.Height];

            Bitmap baseImage = GetBaseImage(previousFrame,
                                            previousFrameBut1,
                                            lsd,
                                            gce,
                                            activeColourTable);

            // copy each source line to the appropriate place in the destination
            int pass = 1;
            int interlaceRowIncrement = 8;
            int interlaceRowNumber    = 0;          // the row of pixels we're currently

            // setting in an interlaced image.
            for (int i = 0; i < id.Size.Height; i++)
            {
                int pixelRowNumber = i;
                if (id.IsInterlaced)
                {
                    #region work out the pixel row we're setting for an interlaced image
                    if (interlaceRowNumber >= id.Size.Height)
                    {
                        pass++;
                        switch (pass)
                        {
                        case 2:
                            interlaceRowNumber = 4;
                            break;

                        case 3:
                            interlaceRowNumber    = 2;
                            interlaceRowIncrement = 4;
                            break;

                        case 4:
                            interlaceRowNumber    = 1;
                            interlaceRowIncrement = 2;
                            break;
                        }
                    }
                    #endregion
                    pixelRowNumber      = interlaceRowNumber;
                    interlaceRowNumber += interlaceRowIncrement;
                }

                // Colour in the pixels for this row
                pixelRowNumber += id.Position.Y;
                if (pixelRowNumber < lsd.LogicalScreenSize.Height)
                {
                    int k    = pixelRowNumber * lsd.LogicalScreenSize.Width;
                    int dx   = k + id.Position.X;                   // start of line in dest
                    int dlim = dx + id.Size.Width;                  // end of dest line
                    if ((k + lsd.LogicalScreenSize.Width) < dlim)
                    {
                        // TESTME: CreateBitmap - past dest edge
                        dlim = k + lsd.LogicalScreenSize.Width;     // past dest edge
                    }
                    int sx = i * id.Size.Width;                     // start of line in source
                    while (dx < dlim)
                    {
                        // map color and insert in destination
                        int indexInColourTable = (int)imageData.Pixels[sx++];
                        // Set this pixel's colour if its index isn't the
                        // transparent colour index, or if this frame doesn't
                        // have a transparent colour.
                        Color c;
                        if (gce.HasTransparentColour && indexInColourTable == gce.TransparentColourIndex)
                        {
                            c = Color.Empty;                             // transparent pixel
                        }
                        else
                        {
                            if (indexInColourTable < activeColourTable.Length)
                            {
                                c = activeColourTable[indexInColourTable];
                            }
                            else
                            {
                                // TESTME: CreateBitmap - BadColourIndex
                                c = Color.Black;
                                string message
                                    = "Colour index: "
                                      + indexInColourTable
                                      + ", colour table length: "
                                      + activeColourTable.Length
                                      + " (" + dx + "," + pixelRowNumber + ")";
                                status = new GifComponentStatus(ErrorState.BadColourIndex,
                                                                message);
                            }
                        }
                        pixelsForThisFrame[dx] = c;
                        dx++;
                    }
                }
            }
            return(CreateBitmap(baseImage, pixelsForThisFrame));
        }
示例#11
0
        public GifFrame(Stream inputStream,
                        LogicalScreenDescriptor lsd,
                        ColourTable gct,
                        GraphicControlExtension gce,
                        GifFrame previousFrame,
                        GifFrame previousFrameBut1,
                        bool xmlDebugging)
            : base(xmlDebugging)
        {
            #region guard against null arguments
            if (lsd == null)
            {
                throw new ArgumentNullException("lsd");
            }

            if (gce == null)
            {
                SetStatus(ErrorState.NoGraphicControlExtension, "");
                // use a default GCE
                gce = new GraphicControlExtension(GraphicControlExtension.ExpectedBlockSize,
                                                  DisposalMethod.NotSpecified,
                                                  false,
                                                  false,
                                                  100,
                                                  0);
            }
            #endregion

            int transparentColourIndex = gce.TransparentColourIndex;

            ImageDescriptor imageDescriptor = new ImageDescriptor(inputStream,
                                                                  XmlDebugging);
            WriteDebugXmlNode(imageDescriptor.DebugXmlReader);

            #region determine the colour table to use for this frame
            Color backgroundColour = Color.FromArgb(0);               // TODO: is this the right background colour?
            // TODO: use backgroundColourIndex from the logical screen descriptor?
            ColourTable activeColourTable;
            if (imageDescriptor.HasLocalColourTable)
            {
                _localColourTable
                    = new ColourTable(inputStream,
                                      imageDescriptor.LocalColourTableSize,
                                      XmlDebugging);
                WriteDebugXmlNode(_localColourTable.DebugXmlReader);
                activeColourTable = _localColourTable;                 // make local table active
            }
            else
            {
                if (gct == null)
                {
                    // We have neither local nor global colour table, so we
                    // won't be able to decode this frame.
                    Bitmap emptyBitmap = new Bitmap(lsd.LogicalScreenSize.Width,
                                                    lsd.LogicalScreenSize.Height);
                    _image = emptyBitmap;
                    _delay = gce.DelayTime;
                    SetStatus(ErrorState.FrameHasNoColourTable, "");
                    return;
                }
                activeColourTable = gct;                 // make global table active
                if (lsd.BackgroundColourIndex == transparentColourIndex)
                {
                    backgroundColour = Color.FromArgb(0);
                }
            }
            #endregion

            // decode pixel data
            int pixelCount = imageDescriptor.Size.Width * imageDescriptor.Size.Height;
            TableBasedImageData indexedPixels
                = new TableBasedImageData(inputStream, pixelCount, XmlDebugging);
            WriteDebugXmlNode(indexedPixels.DebugXmlReader);

            if (indexedPixels.Pixels.Count == 0)
            {
                // TESTME: constructor - indexedPixels.Pixels.Count == 0
                Bitmap emptyBitmap = new Bitmap(lsd.LogicalScreenSize.Width,
                                                lsd.LogicalScreenSize.Height);
                _image = emptyBitmap;
                _delay = gce.DelayTime;
                SetStatus(ErrorState.FrameHasNoImageData, "");
                WriteDebugXmlFinish();
                return;
            }

            // Skip any remaining blocks up to the next block terminator (in
            // case there is any surplus data before the next frame)
            SkipBlocks(inputStream);

            _indexedPixels = indexedPixels;

            _extension = gce;
            if (gce != null)
            {
                _delay = gce.DelayTime;
            }
            _imageDescriptor  = imageDescriptor;
            _backgroundColour = backgroundColour;
            GifComponentStatus status;
            _image = CreateBitmap(indexedPixels,
                                  lsd,
                                  imageDescriptor,
                                  activeColourTable,
                                  gce,
                                  previousFrame,
                                  previousFrameBut1,
                                  out status);

            WriteDebugXmlFinish();
        }
        public void ConstructorTest()
        {
            ReportStart();
            int blockSize = 4;
            DisposalMethod method = DisposalMethod.DoNotDispose;
            bool expectsUserInput = false;
            bool hasTransparentColour = true;
            int delayTime = 40;
            int transparentColourIndex = 22;
            _gce = new GraphicControlExtension( blockSize,
                                                method,
                                                expectsUserInput,
                                                hasTransparentColour,
                                                delayTime,
                                                transparentColourIndex );

            Assert.AreEqual( blockSize, _gce.BlockSize );
            Assert.AreEqual( method, _gce.DisposalMethod );
            Assert.AreEqual( expectsUserInput, _gce.ExpectsUserInput );
            Assert.AreEqual( hasTransparentColour, _gce.HasTransparentColour );
            Assert.AreEqual( delayTime, _gce.DelayTime );
            Assert.AreEqual( transparentColourIndex, _gce.TransparentColourIndex );
            Assert.AreEqual( ErrorState.Ok, _gce.ErrorState );
            ReportEnd();
        }
        private void ConstructorStreamTestDisposalMethodNotSpecified( bool xmlDebugging )
        {
            int blockSize = 4;
            DisposalMethod method = DisposalMethod.NotSpecified;
            bool expectsUserInput = false;
            bool hasTransparentColour = true;
            int delayTime = 40;
            int transparentColourIndex = 22;

            MemoryStream s = new MemoryStream();
            s.WriteByte( (byte) blockSize );

            // Packed fields:
            //	bits 1-3 = reserved
            //	bits 4-6 = disposal method
            //	bit 7 = user input flag
            //	bit 8 = transparent flag
            byte packedFields = (byte)
                (
                      ( (int) method & 7 ) << 2
                    | ( expectsUserInput ? 1 : 0 ) << 1
                    | ( hasTransparentColour ? 1 : 0 )
                );
            s.WriteByte( packedFields );

            // Write delay time, least significant byte first
            s.WriteByte( (byte) ( delayTime & 0xff ) );
            s.WriteByte( (byte) ( ( delayTime & 0xff00 ) >> 8 ) );

            s.WriteByte( (byte) transparentColourIndex );

            s.WriteByte( 0 ); // block terminator

            s.Seek( 0, SeekOrigin.Begin );

            _gce = new GraphicControlExtension( s, xmlDebugging );

            Assert.AreEqual( blockSize, _gce.BlockSize );
            Assert.AreEqual( DisposalMethod.DoNotDispose, _gce.DisposalMethod );
            Assert.AreEqual( expectsUserInput, _gce.ExpectsUserInput );
            Assert.AreEqual( hasTransparentColour, _gce.HasTransparentColour );
            Assert.AreEqual( delayTime, _gce.DelayTime );
            Assert.AreEqual( transparentColourIndex, _gce.TransparentColourIndex );
            Assert.AreEqual( ErrorState.Ok, _gce.ConsolidatedState );

            if( xmlDebugging )
            {
                Assert.AreEqual( ExpectedDebugXml, _gce.DebugXml );
            }
        }
示例#14
0
		/// <summary>
		/// Gets the base image for this frame. This will be overpainted with
		/// the pixels for this frame, where they are not transparent.
		/// </summary>
		/// <param name="previousFrame">
		/// The frame which preceded this frame in the GIF stream.
		/// Null if this is the first frame in the stream.
		/// </param>
		/// <param name="previousFrameBut1">
		/// The frame which preceded the previous frame in the GIF stream.
		/// Null if this is the first or seond frame in the stream.
		/// </param>
		/// <param name="lsd">
		/// The logical screen descriptor for this GIF stream.
		/// </param>
		/// <param name="gce">
		/// The graphic control extension for this frame.
		/// </param>
		/// <param name="act">
		/// The active colour table for this frame.
		/// </param>
		/// <returns></returns>
		private static Bitmap GetBaseImage( GifFrame previousFrame, 
		                                    GifFrame previousFrameBut1, 
		                                    LogicalScreenDescriptor lsd, 
		                                    GraphicControlExtension gce, 
		                                    ColourTable act )
		{
			#region Get the disposal method of the previous frame read from the GIF stream
			DisposalMethod previousDisposalMethod;
			if( previousFrame == null )
			{
				previousDisposalMethod = DisposalMethod.NotSpecified;
			}
			else
			{
				previousDisposalMethod = previousFrame.GraphicControlExtension.DisposalMethod;
			}
			#endregion

			Bitmap baseImage;
			int width = lsd.LogicalScreenSize.Width;
			int height = lsd.LogicalScreenSize.Height;
			
			#region paint baseImage
			switch( previousDisposalMethod )
			{
				case DisposalMethod.DoNotDispose:
					// pre-populate image with previous frame
					baseImage = new Bitmap( previousFrame.TheImage );
					break;
					
				case DisposalMethod.RestoreToBackgroundColour:
					// pre-populate image with background colour
					Color backgroundColour ;
					if( lsd.BackgroundColourIndex == gce.TransparentColourIndex )
					{
						backgroundColour = Color.Empty;
					}
					else
					{
						// TESTME: background colour index different to transparent colour
						backgroundColour = act[lsd.BackgroundColourIndex];
					}
					baseImage = new Bitmap( width, height );
					for( int y = 0; y < height; y++ )
					{
						for( int x = 0; x < height; x++ )
						{
							baseImage.SetPixel( x, y, backgroundColour );
						}
					}
					break;
					
				case DisposalMethod.RestoreToPrevious:
					// pre-populate image with previous frame but 1
					// TESTME: DisposalMethod.RestoreToPrevious
					baseImage = new Bitmap( previousFrameBut1.TheImage );
					break;
					
				default: // DisposalMethod.NotSpecified
					if( previousFrame == null )
					{
						// this is the first frame so start with an empty bitmap
						baseImage = new Bitmap( width, height );
					}
					else
					{
						// pre-populate image with previous frame
						// TESTME: DisposalMethod.NotSpecified on 2nd frame or later
						baseImage = new Bitmap( previousFrame.TheImage );
					}
					break;
			}
			#endregion

			return baseImage;
		}
        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();
        }
 internal static void CheckGraphicControlExtension( GraphicControlExtension ext )
 {
     Assert.AreEqual( GraphicControlExtension.ExpectedBlockSize,
                      ext.BlockSize,
                      "ExpectedBlockSize" );
     Assert.AreEqual( DelayTime, ext.DelayTime, "DelayTime" );
     Assert.AreEqual( DisposalMethod, ext.DisposalMethod, "DisposalMethod" );
     Assert.AreEqual( TransparentColourIndex,
                      ext.TransparentColourIndex,
                      "TransparentColourIndex" );
     Assert.AreEqual( HasTransparentColour, ext.HasTransparentColour, "HasTransparentColour" );
     Assert.AreEqual( ExpectsUserInput, ext.ExpectsUserInput, "ExpectsUserInput" );
 }
示例#17
0
		/// <summary>
		/// Writes a Graphic Control Extension to the supplied output stream.
		/// </summary>
		/// <param name="frame">
		/// The GifFrame to which this graphic control extension relates.
		/// </param>
		/// <param name="transparentColourIndex">
		/// The index within the active colour table of the transparent colour.
		/// </param>
		/// <param name="outputStream">
		/// The stream to write to.
		/// </param>
		private void WriteGraphicCtrlExt( GifFrame frame,
		                                  int transparentColourIndex, 
		                                  Stream outputStream )
		{
			outputStream.WriteByte( GifComponent.CodeExtensionIntroducer );
			outputStream.WriteByte( GifComponent.CodeGraphicControlLabel );
			
			// The frame doesn't have have a graphic control extension yet, so we
			// need to work out what it would contain.
			DisposalMethod disposalMethod;
			bool hasTransparentColour;
			if( _transparent == Color.Empty ) // TODO: remove reference to _transparent - parameterise?
			{
				hasTransparentColour = false;
				disposalMethod = DisposalMethod.NotSpecified; // dispose = no action
			} 
			else 
			{
				// TESTME: WriteGraphicCtrlExt - _transparent != Color.Empty
				hasTransparentColour = true;
				disposalMethod = DisposalMethod.RestoreToBackgroundColour; // force clear if using transparent color
			}
			int blockSize = 4;
			GraphicControlExtension gce
				= new GraphicControlExtension( blockSize, 
				                               disposalMethod, 
				                               frame.ExpectsUserInput, 
				                               hasTransparentColour, 
				                               frame.Delay, 
				                               transparentColourIndex );
			gce.WriteToStream( outputStream );
		}