UpdateGif.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 GrapeCity.Documents.Imaging;
  9. using GrapeCity.Documents.Drawing;
  10.  
  11. namespace DsImagingWeb.Demos
  12. {
  13. // This sample loads an existing GIF and modifies its frames.
  14. // Specifically, it applies a color matrix to change the colors,
  15. // and flips the images horizontally.
  16. // The GIF loaded in this sample is the one produced by IndexedGif.
  17. public class UpdateGif
  18. {
  19. public string DefaultMime { get => Common.Util.MimeTypes.GIF; }
  20.  
  21. public Stream GenerateImageStream(string targetMime, Size pixelSize, float dpi, bool opaque, string[] sampleParams = null)
  22. {
  23. if (targetMime != Common.Util.MimeTypes.GIF)
  24. throw new Exception("This sample only supports GIF output format.");
  25.  
  26. // Matrix to change colors to greenish blues:
  27. var colorMatrix = new ColorMatrix5x4()
  28. {
  29. M11 = 0.2f,
  30. M12 = 0.3f,
  31. M22 = 0.5f
  32. };
  33.  
  34. var ms = new MemoryStream();
  35. // Read source GIF, write modified one (change palette and flip and rotate frames):
  36. using (var gr = new GcGifReader(Path.Combine("Resources", "Gifs", "goldfish-indexed.gif")))
  37. using (var gw = new GcGifWriter(ms))
  38. {
  39. var pal = gr.GetGlobalPalette();
  40. // This sample will only work with GIFs that have a global palette:
  41. if (pal == null)
  42. throw new Exception("Source GIF does not have a global palette.");
  43. // Use color matrix to update the palette:
  44. using (var palBmp = new GcBitmap(pal, pal.Length, 1, true))
  45. palBmp.ApplyColorMatrix(colorMatrix);
  46.  
  47. // Set target palette and other properties:
  48. gw.GlobalPalette = pal;
  49. gw.LogicalScreenWidth = gr.LogicalScreenWidth;
  50. gw.LogicalScreenHeight = gr.LogicalScreenHeight;
  51. gw.PixelAspectRatio = gr.PixelAspectRatio;
  52. gw.AllowAddingTransparentColor = false;
  53. using (var tbmp = new GcBitmap())
  54. for (int i = 0; i < gr.Frames.Count; i++)
  55. {
  56. var frame = gr.Frames[i];
  57. frame.ToGcBitmap(tbmp, i - 1);
  58.  
  59. // Flip the image horizontally (this will reverse the 'rotation' of the fish):
  60. using (var bmp = tbmp.FlipRotate(FlipRotateAction.FlipHorizontal))
  61. {
  62. // Apply the color matrix and append the frame to the target GIF:
  63. bmp.ApplyColorMatrix(colorMatrix);
  64. gw.AppendFrame(bmp, pal, DitheringMethod.NoDithering, 0, 0, GifDisposalMethod.DoNotDispose, frame.DelayTime, false);
  65. }
  66. }
  67. }
  68. ms.Seek(0, SeekOrigin.Begin);
  69. return ms;
  70. }
  71. }
  72. }
  73.