Bumpkit icon indicating copy to clipboard operation
Bumpkit copied to clipboard

Save Gif from Gif source

Open Dunge opened this issue 9 years ago • 4 comments

The demo use a static image, create multiple frame by rotation and save a gif. But if the original Image loaded is a Gif, it seems to create a corrupted file.

See this code:

        private static byte[] ToGifByteArray(Image image)
        {
            var frameCount = image.GetFrameCount(FrameDimension.Time);
            var times = image.GetPropertyItem(0x5100).Value;  // PropertyTagFrameDelay

            using (var memoryStream = new MemoryStream())
            {
                using (var encoder = new GifEncoder(memoryStream, null, null, -1))
                {
                    for (var idx = 0; idx < frameCount; idx++)
                    {
                        image.SelectActiveFrame(FrameDimension.Time, idx);
                        var dur = BitConverter.ToInt32(times, 4 * 0); 
                        encoder.AddFrame(image, 0, 0, TimeSpan.FromSeconds(dur));
                    }
                }

                File.WriteAllBytes(@"C:\test.gif", memoryStream.ToArray());
                return memoryStream.ToArray();
            }
        }

If I pass a Image loaded from a gif, it create a corrupted. If I comment the first two lines for the timing and the loop for the frame and pass a Image loaded from a jpeg, it create a working gif.

Dunge avatar Sep 09 '16 20:09 Dunge

Hi Dunge,

I am not actively maintaining this project. If you find a solution please feel free to submit a pull request for the change. I will leave these issues open for others to address.

DataDink avatar Apr 05 '17 14:04 DataDink

Although this issue is old, it is not an issue. This is due to the format animated gif (and gifs in general). A work around is to save it to a memory stream as any other format (png will retain the image's transparency/pallet info), and then reload it back into an image and pass it to the encoder.

using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
{
    // convert the source image format and save it to memory.
    sourceImage.Save(ms, ImageFormat.Png);
    ms.Seek(0, SeekOrigin);
    // create a new image from the memory stream
    sourceImage = Image.FromStream(ms);

    // now we can pass sourceImage into the GifEncoder...
    myGifEncoder.AddFrame(sourceimage);
}

RyanThiele avatar May 28 '20 16:05 RyanThiele

@RyanThiele would you be willing to make a pull request for this?

DataDink avatar Jun 08 '20 16:06 DataDink

@DataDink #12 pull request for this issue was made.

RyanThiele avatar Jun 08 '20 17:06 RyanThiele