'' This code is part of Document Solutions for Imaging demos.
'' Copyright (c) MESCIUS 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 targetMime As String,
                ByVal pixelSize As Size,
                ByVal dpi As Single,
                ByVal opaque As Boolean,
                Optional sampleParams As String() = Nothing) As Stream

        If Not targetMime = MimeTypes.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 DefaultMime() As String
            Return MimeTypes.GIF
        End Get
    End Property
End Class