IndexedGif.cs
//
// This code is part of Document Solutions for Imaging demos.
// Copyright (c) MESCIUS inc. All rights reserved.
//
using System;
using System.IO;
using System.Drawing;
using GrapeCity.Documents.Imaging;
using GrapeCity.Documents.Drawing;
using DsImagingWeb.Demos.Common;

namespace DsImagingWeb.Demos
{
    // This sample loads an existing GIF with true color frames
    // (produced by the MakeGif sample) and converts its frames
    // to indexed 8bpp images. It also adds a global palette to the
    // resulting GIF (the palette is taken from the first frame).
    public class IndexedGif
    {
        public string DefaultMime { get => Common.Util.MimeTypes.GIF; }

        public Stream GenerateImageStream(string targetMime, Size pixelSize, float dpi, bool opaque, string[] sampleParams = null)
        {
            if (targetMime != Util.MimeTypes.GIF)
                throw new Exception("This sample only supports GIF output format.");

            var ms = new MemoryStream();
            // Read frames from the source GIF, convert them to 8bpp and save in the target GIF:
            using (var gr = new GcGifReader(Path.Combine("Resources", "Gifs", "goldfish.gif")))
            using (var gw = new GcGifWriter(ms))
            {
                for (int i = 0; i < gr.Frames.Count; ++i)
                {
                    // Add a global palette to the target GIF based on the first frame:
                    if (i == 0)
                        using (var tbmp = gr.Frames[i].ToGcBitmap())
                            gw.GlobalPalette = tbmp.GenerateOctreePalette(256);

                    var indexedBmp = gr.Frames[i].ReadAsIndexed8bppBitmap();
                    gw.AppendFrame(indexedBmp, 0, 0, GifDisposalMethod.DoNotDispose, 16);
                }
            }
            ms.Seek(0, SeekOrigin.Begin);
            return ms;
        }
    }
}