'' This code is part of GrapeCity Documents for Imaging samples.
'' Copyright (c) GrapeCity, Inc. All rights reserved.
Imports System.IO
Imports System.Drawing
Imports System.Collections.Generic
Imports System.Linq
Imports System.Numerics
Imports GrapeCity.Documents.Drawing
Imports GrapeCity.Documents.Text
Imports GrapeCity.Documents.Imaging

'' 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
    Function GenerateImageStream(
                ByVal targetEncoding As ImageEncoding,
                ByVal pixelSize As Size,
                ByVal dpi As Single,
                ByVal opaque As Boolean,
                Optional sampleParams As String() = Nothing) As Stream

        If Not targetEncoding = ImageEncoding.Gif Then
            Throw New Exception("This sample only supports GIF output format.")
        End If

        Dim ms = New MemoryStream()
        '' Read frames from the source GIF, convert them to 8bpp And save in the target GIF
        Using gr = New GcGifReader(Path.Combine("Resources", "Gifs", "goldfish.gif")), gw = New GcGifWriter(ms)
            For i = 0 To gr.Frames.Count - 1
                '' Add a global palette to the target GIF based on the first frame
                If i = 0 Then
                    Using tbmp = gr.Frames(i).ToGcBitmap()
                        gw.GlobalPalette = tbmp.GenerateOctreePalette(256)
                    End Using
                End If
                Dim indexedBmp = gr.Frames(i).ReadAsIndexed8bppBitmap()
                gw.AppendFrame(indexedBmp, 0, 0, GifDisposalMethod.DoNotDispose, 16)
        End Using
        ms.Seek(0, SeekOrigin.Begin)
        Return ms
    End Function

    Public ReadOnly Property DefaultEncoding() As ImageEncoding
            Return ImageEncoding.Gif
        End Get
    End Property
End Class