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

namespace GcImagingWeb.Samples
{
    // This sample takes a color JPEG, converts it to different image types
    // (such as b/w and grayscale) and creates a multi-frame TIFF from those
    // images.
    public class ImageTypesInTiff
    {
        public Stream GenerateImageStream(ImageEncoding targetEncoding, int pixelWidth = 1024, int pixelHeight = 1024, bool opaque = true, float dpiX = 96, float dpiY = 96)
        {
            if (targetEncoding != ImageEncoding.Tiff)
                throw new Exception("This sample only supports TIFF output format.");

            var path = Path.Combine("Resources", "Images", "minerva.jpg");

            var ms = new MemoryStream();
            using (var tw = new GcTiffWriter(ms))
            using (var bmp = new GcBitmap(path))
            {
                // Using the green channel produces a marginally better result for this photo.
                // For a much better bilevel image produced by dithering, see DitheringInTiff.
                using (var f = bmp.ToBilevelBitmap(ColorChannel.Green))
                    tw.AppendFrame(f);
                using (var f = bmp.ToGrayscaleBitmap())
                    tw.AppendFrame(f);
                // 4bpp allows from 8 to 16 colors, we use max (16):
                using (var f = bmp.ToIndexed4bppBitmap(16))
                    tw.AppendFrame(f);
                // 8bpp allows from 8 to 256 colors, we use max (256):
                using (var f = bmp.ToIndexed8bppBitmap(256))
                    tw.AppendFrame(f);
                tw.AppendFrame(bmp);
            }
            ms.Seek(0, SeekOrigin.Begin);
            return ms;
        }

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