I've written a short method for converting images(Image class) to a GifEncoder and finally saving that Gif to a file. However, when I go to open the resulting Gif created, it has some problems. 1) The Gif stops playing after 2 cycles in a browser. 2) When loaded through an image editor the colors seem to mix up a bit between pixels.
public void ConvertToGif( string DestinationPath , Image myImage , int myFrames ) {
Bitmap myBitmap = new Bitmap( myImage.Width / myFrames , myImage.Height );
GifBitmapEncoder myEncoder = new GifBitmapEncoder();
int i = 0;
while( i < myFrames ) {
Graphics GrDrw = Graphics.FromImage( myBitmap );
var DestRegion = new Rectangle( 0 , 0 , myBitmap.Width , myBitmap.Height );
var SrceRegion = new Rectangle( myBitmap.Width * i , 0 , myBitmap.Width , myBitmap.Height );
GrDrw.DrawImage( myImage , DestRegion , SrceRegion , GraphicsUnit.Pixel );
BitmapSource mySource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap( myBitmap.GetHbitmap() , IntPtr.Zero , Int32Rect.Empty , BitmapSizeOptions.FromEmptyOptions() );
myEncoder.Frames.Add( BitmapFrame.Create( mySource , mySource ) );
GrDrw.Dispose();
i += 1;
}
System.IO.FileStream myStream = new System.IO.FileStream( @DestinationPath , System.IO.FileMode.Create );
myEncoder.Save( myStream );
}
The number of frames from an image created with ConvertToGif() also don't seem to register when running the resulting Gif through my other method, ConvertFromGif():
public Image ConvertFromGif( Image myImage ) {
var myDimensions = new FrameDimension( myImage.FrameDimensionsList[ 0 ] );
var myFrames = myImage.GetFrameCount( myDimensions );
var newImage = new Bitmap( myImage.Width * myFrames , myImage.Height );
for( int i = 0; i < myFrames; i ++ ) {
myImage.SelectActiveFrame( myDimensions , i );
var DestRegion = new Rectangle( myImage.Width * i , 0 , myImage.Width , myImage.Height );
var SrceRegion = new Rectangle( 0 , 0 , myImage.Width , myImage.Height );
Graphics GrDrw = Graphics.FromImage( newImage );
GrDrw.DrawImage( myImage , DestRegion , SrceRegion , GraphicsUnit.Pixel );
GrDrw.Dispose();
}
return newImage;
}
I can run any Gif through my ConvertFromGif() method, but Gifs made by my ConvertToGif() method won't work.