public GifFrame( Stream inputStream, LogicalScreenDescriptor lsd, ColourTable gct, GraphicControlExtension gce, GifFrame previousFrame, GifFrame previousFrameBut1 ) : base( inputStream, lsd, gct, gce, previousFrame, previousFrameBut1 ) {}
public GifFrame(Stream inputStream, LogicalScreenDescriptor lsd, ColourTable gct, GraphicControlExtension gce, GifFrame previousFrame, GifFrame previousFrameBut1) : this(inputStream, lsd, gct, gce, previousFrame, previousFrameBut1, false) { }
/// <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); }
/// <summary> /// Converts the supplied image to a collection of pixel indices using /// the supplied colour table. /// Only used when the QuantizerType is set to UseSuppliedPalette /// </summary> /// <param name="act">The active colour table</param> /// <param name="image">The image</param> /// <returns></returns> private IndexedPixels MakeIndexedPixels( ColourTable act, Image image ) { int pixelCount = image.Height * image.Width; string counterText = "Getting indices in colour table"; AddCounter( counterText, pixelCount ); Bitmap bitmap = (Bitmap) image; IndexedPixels ip = new IndexedPixels(); for( int y = 0; y < image.Height; y++ ) { for( int x = 0; x < image.Width; x++ ) { Color c = bitmap.GetPixel( x, y ); int index = FindClosest( c, act ); ip.Add( (byte) index ); MyProgressCounters[counterText].Value = ip.Count; } } RemoveCounter( counterText ); return ip; }
/// <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 ); }
/// <summary> /// Returns a colour table containing the colours of the quantized image. /// </summary> /// <returns> /// A colour table containing up to 256 colours, being the colours of /// the image after quantization. /// </returns> private ColourTable ColourMap() { ColourTable map = new ColourTable(); int[] originalIndices = new int[_neuronCount]; int[] thisNeuron; // Build an array of the original indices of the neurons in the // network, before the BuildIndex method reordered them. for( int neuronIndex = 0; neuronIndex < _neuronCount; neuronIndex++ ) { thisNeuron = _network[neuronIndex]; originalIndices[thisNeuron[3]] = neuronIndex; } for( int i = 0; i < _neuronCount; i++ ) { int indexInNetwork = originalIndices[i]; map.Add( Color.FromArgb( 255, _network[indexInNetwork][0], _network[indexInNetwork][1], _network[indexInNetwork][2] ) ); } return map; }
/// <summary> /// Calculates the colour table needed to index the supplied pixels. /// </summary> /// <param name="colourQuantizationQuality"> /// Sets quality of color quantization (conversion of images /// to the maximum 256 colors allowed by the GIF specification). /// Lower values (minimum = 1) produce better colors, but slow /// processing significantly. 10 is the default, and produces /// good color mapping at reasonable speeds. Values greater /// than 20 do not yield significant improvements in speed. /// Defaults to 1 if not greater than zero. /// </param> private void CreateColourTableUsingNeuQuant( int colourQuantizationQuality ) { byte[] rgb = ImageTools.GetRgbArray( _imageColours ); _nq = new NeuQuant( rgb, colourQuantizationQuality ); _colourTable = _nq.Process(); // create reduced palette }
private static void CheckFrame( Stream s, ColourTable globalColourTable, Bitmap bitmap) { CheckExtensionIntroducer( s ); CheckGraphicControlLabel( s ); CheckGraphicControlExtension( s ); CheckImageSeparator( s ); bool shouldHaveLocalColourTable = (globalColourTable == null) ? true : false; int lctSizeBits = shouldHaveLocalColourTable ? 1 : 0; ImageDescriptor id = CheckImageDescriptor( s, shouldHaveLocalColourTable, lctSizeBits ); if( globalColourTable == null ) { // no global colour table so must be a local colour table on // each frame ColourTable lct = CheckColourTable( s, id.LocalColourTableSize ); CheckImageData( s, lct, id, bitmap ); } else { CheckImageData( s, globalColourTable, id, bitmap ); } CheckBlockTerminator( s ); }
public void WriteToStreamTest() { ReportStart(); _table = new ColourTable(); _table.Add( Color.FromArgb( 255, 255, 0, 0 ) ); // red _table.Add( Color.FromArgb( 255, 0, 255, 0 ) ); // green _table.Add( Color.FromArgb( 255, 0, 0, 255 ) ); // blue _table.Add( Color.FromArgb( 255, 255, 255, 255 ) ); // white MemoryStream s = new MemoryStream(); _table.WriteToStream( s ); s.Seek( 0, SeekOrigin.Begin ); ColourTable t = new ColourTable( s, 4 ); Assert.AreEqual( ErrorState.Ok, t.ConsolidatedState ); Assert.AreEqual( _table.Colours.Length, t.Colours.Length ); for( int i = 0; i < t.Colours.Length; i++ ) { Assert.AreEqual( _table[i], t[i], "Colour index " + i ); } ReportEnd(); }
public void IndexerTest() { ReportStart(); Stream s = PrepareStream(); _table = new ColourTable ( s, 4 ); Random r = new Random(); for( int i = 0; i < _table.Length; i++ ) { Color c = Color.FromArgb( r.Next() ); _table[i] = c; Assert.AreEqual( c, _table[i], "Index " + i ); Assert.AreEqual( c, _table.Colours[i], "Index " + i ); } ReportEnd(); }
public void IndexerSetTestIndexOutOfRange() { ReportStart(); Stream s = PrepareStream(); _table = new ColourTable( s, 4 ); try { _table[4] = Color.FromArgb( 0 ); } catch( ArgumentOutOfRangeException ex ) { string message = "Colour table size: 4. Index: " + 4; StringAssert.Contains( message, ex.Message ); Assert.AreEqual( "index", ex.ParamName ); ReportEnd(); throw; } }
/// <summary> /// Writes a Logical Screen Descriptor to the supplied stream. /// Also writes a global colour table if required. /// </summary> /// <param name="outputStream"> /// The stream to write to. /// </param> private void WriteLogicalScreenDescriptor( Stream outputStream ) { bool hasGlobalColourTable = _strategy == ColourTableStrategy.UseGlobal; int colourResolution = 7; // TODO: parameterise colourResolution? bool globalColourTableIsSorted = false; // Sorting of colour tables is not currently supported int backgroundColorIndex = 0; // TODO: parameterise backgroundColourIndex? int pixelAspectRatio = 0; // TODO: parameterise pixelAspectRatio? if( _strategy == ColourTableStrategy.UseGlobal ) { if( _quantizerType == QuantizerType.UseSuppliedPalette ) { // use supplied palette _globalColourTable = new ColourTable(); string buildColourTableCounterText = "Building colour table from supplied palette"; AddCounter( buildColourTableCounterText, _palette.Count ); int paletteIndex = 0; foreach( Color c in _palette ) { _globalColourTable.Add( c ); MyProgressCounters[buildColourTableCounterText].Value = paletteIndex; paletteIndex++; } _globalColourTable.Pad(); RemoveCounter( buildColourTableCounterText ); } else { // Analyse the pixels in all the images to build the // global colour table. Collection<Image> images = new Collection<Image>(); foreach( GifFrame thisFrame in _frames ) { Image thisImage = thisFrame.TheImage; images.Add( thisImage ); } _pixelAnalysis = new PixelAnalysis( images ); _pixelAnalysis.ColourQuality = _quality; _pixelAnalysis.Analyse(); _globalColourTable = _pixelAnalysis.ColourTable; } LogicalScreenDescriptor lsd = new LogicalScreenDescriptor( _logicalScreenSize, hasGlobalColourTable, colourResolution, globalColourTableIsSorted, _globalColourTable.SizeBits, backgroundColorIndex, pixelAspectRatio ); lsd.WriteToStream( outputStream ); _globalColourTable.WriteToStream( outputStream ); } else { LogicalScreenDescriptor lsd = new LogicalScreenDescriptor( _logicalScreenSize, hasGlobalColourTable, colourResolution, globalColourTableIsSorted, 7, backgroundColorIndex, pixelAspectRatio ); lsd.WriteToStream( outputStream ); } }
/// <summary> /// Writes an image descriptor to the supplied stream. /// </summary> /// <param name="imageSize"> /// The size, in pixels, of the image in this frame. /// </param> /// <param name="position"> /// The position of this image within the logical screen. /// </param> /// <param name="localColourTable"> /// The local colour table for this frame. /// Supply null if the global colour table is to be used for this frame. /// </param> /// <param name="outputStream"> /// The stream to write to. /// </param> private static void WriteImageDescriptor( Size imageSize, Point position, ColourTable localColourTable, Stream outputStream ) { bool hasLocalColourTable; int localColourTableSize; if( localColourTable == null ) { hasLocalColourTable = false; localColourTableSize = 0; } else { hasLocalColourTable = true; localColourTableSize = localColourTable.SizeBits; } bool isInterlaced = false; // encoding of interlaced images not currently supported bool localColourTableIsSorted = false; // sorting of colour tables not currently supported ImageDescriptor id = new ImageDescriptor( position, imageSize, hasLocalColourTable, isInterlaced, localColourTableIsSorted, localColourTableSize ); outputStream.WriteByte( GifComponent.CodeImageSeparator ); id.WriteToStream( outputStream ); }
private ColourTable SetActiveColourTable() { ColourTable act; // active colour table if( _strategy == ColourTableStrategy.UseLocal ) { if( _quantizerType == QuantizerType.UseSuppliedPalette ) { if( _frames[_encodingFrame].Palette == null ) { // TESTME: SetActiveColourTable - SetActiveColourTable, UseSuppliedPalette, no palette supplied string message = "You have opted to use a local colour table built " + "from a supplied palette, but frame " + _encodingFrame + "does not have a palette."; throw new InvalidOperationException( message ); } else { // Build local colour table from colours in the frame's // supplied palette. act = new ColourTable(); foreach( Color c in _frames[_encodingFrame].Palette ) { act.Add( c ); } act.Pad(); } } else { // Build local colour table based on colours in the image. Image thisImage = _frames[_encodingFrame].TheImage; _pixelAnalysis = new PixelAnalysis( thisImage, _quantizerType ); _pixelAnalysis.ColourQuality = _quality; _pixelAnalysis.Analyse(); // make local colour table active act = _pixelAnalysis.ColourTable; } } else { // make global colour table active act = _globalColourTable; } return act; }
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(); }
private static ColourTable CheckColourTable( Stream s, int colourTableSize) { // read colour table ColourTable ct = new ColourTable( s, colourTableSize ); Assert.AreEqual( ErrorState.Ok, ct.ConsolidatedState ); return ct; }
private void ConstructorStreamTest( bool xmlDebugging ) { Stream s = PrepareStream(); _table = new ColourTable( s, 4, xmlDebugging ); Assert.AreEqual( 4, _table.Length ); Assert.AreEqual( 4, _table.Colours.Length ); Assert.AreEqual( Color.FromArgb( 255, 0, 0, 0 ), _table.Colours[0] ); Assert.AreEqual( Color.FromArgb( 255, 255, 0, 0 ), _table.Colours[1] ); Assert.AreEqual( Color.FromArgb( 255, 0, 255, 0 ), _table.Colours[2] ); Assert.AreEqual( Color.FromArgb( 255, 0, 0, 255 ), _table.Colours[3] ); Assert.AreEqual( Color.FromArgb( 255, 0, 0, 0 ), _table[0] ); Assert.AreEqual( Color.FromArgb( 255, 255, 0, 0 ), _table[1] ); Assert.AreEqual( Color.FromArgb( 255, 0, 255, 0 ), _table[2] ); Assert.AreEqual( Color.FromArgb( 255, 0, 0, 255 ), _table[3] ); Assert.AreEqual( ErrorState.Ok, _table.ConsolidatedState ); if( xmlDebugging ) { Assert.AreEqual( ExpectedDebugXml, _table.DebugXml ); } }
private static void CheckImageData( Stream s, ColourTable act, ImageDescriptor id, Bitmap expectedBitmap) { // 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 = id.Size.Width * id.Size.Height; TableBasedImageData tbid = new TableBasedImageData( s, pixelCount ); Assert.AreEqual( ErrorState.Ok, tbid.ConsolidatedState ); for( int y = 0; y < id.Size.Height; y++ ) { for( int x = 0; x < id.Size.Width; x++ ) { int i = (y * id.Size.Width) + x; Assert.AreEqual( expectedBitmap.GetPixel( x, y ), act[tbid.Pixels[i]], "X: " + x + ", Y: " + y ); } } }
private void ConstructorStreamTestColourTableTooShort( bool xmlDebugging ) { Stream s = PrepareStream(); // Pass larger number of colours than are actually in the stream _table = new ColourTable( s, 5, xmlDebugging ); Assert.AreEqual( ErrorState.ColourTableTooShort, _table.ErrorState ); Assert.AreEqual( 5, _table.Length ); Assert.AreEqual( Color.FromArgb( 255, 0, 0, 0 ), _table[0] ); Assert.AreEqual( Color.FromArgb( 255, 255, 0, 0 ), _table[1] ); Assert.AreEqual( Color.FromArgb( 255, 0, 255, 0 ), _table[2] ); Assert.AreEqual( Color.FromArgb( 255, 0, 0, 255 ), _table[3] ); // missing colour should be set to black by the constructor Assert.AreEqual( Color.FromArgb( 0, 0, 0, 0 ), _table[4] ); if( xmlDebugging ) { Assert.AreEqual( ExpectedDebugXml, _table.DebugXml ); } }
/// <summary> /// Creates a colour table directly from the distinct colours in the /// supplied image(s). /// </summary> private void CreateDirectColourTable() { string buildColourTableCounterText = "Creating colour table from images"; AddCounter( buildColourTableCounterText, _distinctColours.Values.Count ); _colourTable = new ColourTable(); int distinctColourIndex = 0; foreach( Color c in _distinctColours.Values ) { MyProgressCounters[buildColourTableCounterText].Value = distinctColourIndex; _colourTable.Add( c ); distinctColourIndex++; } _colourTable.Pad(); RemoveCounter( buildColourTableCounterText ); }
public void ConstructorStreamTestTooFewColours() { ReportStart(); Stream s = new MemoryStream(); try { _table = new ColourTable( s, -1 ); } catch( ArgumentOutOfRangeException ex ) { string message = "The number of colours must be between 0 and 256. " + "Number supplied: -1"; StringAssert.Contains( message, ex.Message ); Assert.AreEqual( "numberOfColours", ex.ParamName ); ReportEnd(); throw; } }
/// <summary> /// Reads GIF image from stream /// </summary> /// <param name="inputStream"> /// Stream containing GIF file. /// </param> /// <exception cref="ArgumentNullException"> /// The supplied stream is null. /// </exception> private void ReadStream( Stream inputStream ) { _frames = new Collection<GifFrame>(); _applicationExtensions = new Collection<ApplicationExtension>(); _gct = null; _readStreamCounterText = "Reading stream byte"; AddCounter( _readStreamCounterText, (int) inputStream.Length ); _header = new GifHeader( inputStream, XmlDebugging ); MyProgressCounters[_readStreamCounterText].Value = (int) inputStream.Position; WriteDebugXmlNode( _header.DebugXmlReader ); if( _header.ErrorState != ErrorState.Ok ) { WriteDebugXmlFinish(); return; } _lsd = new LogicalScreenDescriptor( inputStream, XmlDebugging ); MyProgressCounters[_readStreamCounterText].Value = (int) inputStream.Position; WriteDebugXmlNode( _lsd.DebugXmlReader ); if( TestState( ErrorState.EndOfInputStream ) ) { WriteDebugXmlFinish(); return; } if( _lsd.HasGlobalColourTable ) { _gct = new ColourTable( inputStream, _lsd.GlobalColourTableSize, XmlDebugging ); MyProgressCounters[_readStreamCounterText].Value = (int) inputStream.Position; WriteDebugXmlNode( _gct.DebugXmlReader ); } if( ConsolidatedState == ErrorState.Ok ) { ReadContents( inputStream ); MyProgressCounters[_readStreamCounterText].Value = (int) inputStream.Position; } inputStream.Close(); WriteDebugXmlFinish(); RemoveCounter( _readStreamCounterText ); }
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 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(); }
/// <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)); }
/// <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; }
/// <summary> /// Returns the index within the supplied colour table of the colour /// closest to the supplied colour. /// </summary> /// <param name="colourToFind"> /// The colour to find the closest match for. /// </param> /// <param name="colourTable"> /// The active colour table. /// </param> /// <returns> /// Returns -1 if the supplied colour is null. /// </returns> private static int FindClosest( Color colourToFind, ColourTable colourTable ) { if( colourTable == null ) { // TESTME: FindClosest - null colour table return -1; } int r = colourToFind.R; int g = colourToFind.G; int b = colourToFind.B; int minpos = 0; int dmin = 256 * 256 * 256; int len = colourTable.Length; for( int i = 0; i < len; i++ ) { int dr = r - colourTable[i].R; int dg = g - colourTable[i].G; int db = b - colourTable[i].B; int d = dr * dr + dg * dg + db * db; if( d < dmin ) { dmin = d; minpos = i; } } return minpos; }