IndexedGif.cs
//
// This code is part of GrapeCity Documents for Imaging samples.
// Copyright (c) GrapeCity, Inc. All rights reserved.
//
using System;
using System.IO;
using GrapeCity.Documents.Imaging;
using GrapeCity.Documents.Drawing;

namespace GcImagingWeb.Samples
{
    // 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 Stream GenerateImageStream(ImageEncoding targetEncoding, int pixelWidth = 1024, int pixelHeight = 1024, bool opaque = true, float dpiX = 96, float dpiY = 96)
        {
            if (targetEncoding != ImageEncoding.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;
        }

        public ImageEncoding DefaultEncoding { get => ImageEncoding.Gif; }
    }
}