DitheringInTiff.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 System.Collections.Generic;
using System.Linq;
using GrapeCity.Documents.Drawing;
using GrapeCity.Documents.Text;
using GrapeCity.Documents.Imaging;
using GCTEXT = GrapeCity.Documents.Text;
using GCDRAW = GrapeCity.Documents.Drawing;

namespace DsImagingWeb.Demos
{
    // This sample takes a color JPEG, and creates bi-level bitmaps from it
    // using all available dithering methods. The resulting b/w images
    // are added as frames to a multi-frame TIFF.
    // The original color image is added as the last page.
    public class DitheringInTiff
    {
        public string DefaultMime { get => Common.Util.MimeTypes.TIFF; }

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

            var path = Path.Combine("Resources", "Images", "minerva.jpg");
            var font = GCTEXT.Font.FromFile(Path.Combine("Resources", "Fonts", "cour.ttf"));
            var ms = new MemoryStream();
            using (var tw = new GcTiffWriter(ms))
            using (var bmp = new GcBitmap(path))
            {
                // Create text layout for labels:
                var tl = new TextLayout(bmp.DpiX);
                tl.DefaultFormat.Font = font;
                tl.DefaultFormat.FontSize = 16;
                tl.DefaultFormat.BackColor = Color.White;
                // Loop through all dithering methods (starting with no dithering):
                var methods = typeof(DitheringMethod).GetEnumValues();
                foreach (DitheringMethod method in methods)
                {
                    using (var tbmp = bmp.Clone())
                    {
                        // Apply dithering:
                        tbmp.ApplyEffect(DitheringEffect.Get(method));
                        // Draw label:
                        tl.Clear();
                        tl.Append(method.ToString());
                        tl.PerformLayout(true);
                        using (var g = tbmp.CreateGraphics())
                            g.DrawTextLayout(tl, new PointF(0, tbmp.Height - tl.ContentHeight));
                        // Convert to bi-level bitmap:
                        using (var f = tbmp.ToBilevelBitmap())
                            tw.AppendFrame(f);
                    }
                }
                // Add original image:
                tw.AppendFrame(bmp);
            }
            ms.Seek(0, SeekOrigin.Begin);
            return ms;
        }
    }
}