Save Gif from Gif source
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.
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.
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 would you be willing to make a pull request for this?
@DataDink #12 pull request for this issue was made.