DitheringInTiff.cs
  1. //
  2. // This code is part of Document Solutions for Imaging demos.
  3. // Copyright (c) MESCIUS inc. All rights reserved.
  4. //
  5. using System;
  6. using System.IO;
  7. using System.Drawing;
  8. using System.Collections.Generic;
  9. using System.Linq;
  10. using GrapeCity.Documents.Drawing;
  11. using GrapeCity.Documents.Text;
  12. using GrapeCity.Documents.Imaging;
  13. using GCTEXT = GrapeCity.Documents.Text;
  14. using GCDRAW = GrapeCity.Documents.Drawing;
  15.  
  16. namespace DsImagingWeb.Demos
  17. {
  18. // This sample takes a color JPEG, and creates bi-level bitmaps from it
  19. // using all available dithering methods. The resulting b/w images
  20. // are added as frames to a multi-frame TIFF.
  21. // The original color image is added as the last page.
  22. public class DitheringInTiff
  23. {
  24. public string DefaultMime { get => Common.Util.MimeTypes.TIFF; }
  25.  
  26. public Stream GenerateImageStream(string targetMime, Size pixelSize, float dpi, bool opaque, string[] sampleParams = null)
  27. {
  28. if (targetMime != Common.Util.MimeTypes.TIFF)
  29. throw new Exception("This sample only supports TIFF output format.");
  30.  
  31. var path = Path.Combine("Resources", "Images", "minerva.jpg");
  32. var font = GCTEXT.Font.FromFile(Path.Combine("Resources", "Fonts", "cour.ttf"));
  33. var ms = new MemoryStream();
  34. using (var tw = new GcTiffWriter(ms))
  35. using (var bmp = new GcBitmap(path))
  36. {
  37. // Create text layout for labels:
  38. var tl = new TextLayout(bmp.DpiX);
  39. tl.DefaultFormat.Font = font;
  40. tl.DefaultFormat.FontSize = 16;
  41. tl.DefaultFormat.BackColor = Color.White;
  42. // Loop through all dithering methods (starting with no dithering):
  43. var methods = typeof(DitheringMethod).GetEnumValues();
  44. foreach (DitheringMethod method in methods)
  45. {
  46. using (var tbmp = bmp.Clone())
  47. {
  48. // Apply dithering:
  49. tbmp.ApplyEffect(DitheringEffect.Get(method));
  50. // Draw label:
  51. tl.Clear();
  52. tl.Append(method.ToString());
  53. tl.PerformLayout(true);
  54. using (var g = tbmp.CreateGraphics())
  55. g.DrawTextLayout(tl, new PointF(0, tbmp.Height - tl.ContentHeight));
  56. // Convert to bi-level bitmap:
  57. using (var f = tbmp.ToBilevelBitmap())
  58. tw.AppendFrame(f);
  59. }
  60. }
  61. // Add original image:
  62. tw.AppendFrame(bmp);
  63. }
  64. ms.Seek(0, SeekOrigin.Begin);
  65. return ms;
  66. }
  67. }
  68. }
  69.