PsdBlockLengthWriter.cs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. /////////////////////////////////////////////////////////////////////////////////
  2. //
  3. // Photoshop PSD FileType Plugin for Paint.NET
  4. // http://psdplugin.codeplex.com/
  5. //
  6. // This software is provided under the MIT License:
  7. // Copyright (c) 2006-2007 Frank Blumenberg
  8. // Copyright (c) 2010-2014 Tao Yue
  9. //
  10. // Portions of this file are provided under the BSD 3-clause License:
  11. // Copyright (c) 2006, Jonas Beckeman
  12. //
  13. // See LICENSE.txt for complete licensing and attribution information.
  14. //
  15. /////////////////////////////////////////////////////////////////////////////////
  16. using System;
  17. using System.IO;
  18. using System.Text;
  19. namespace PhotoshopFile
  20. {
  21. /// <summary>
  22. /// Writes the actual length in front of the data block upon disposal.
  23. /// </summary>
  24. class PsdBlockLengthWriter : IDisposable
  25. {
  26. private bool disposed = false;
  27. long lengthPosition;
  28. long startPosition;
  29. bool hasLongLength;
  30. PsdBinaryWriter writer;
  31. public PsdBlockLengthWriter(PsdBinaryWriter writer)
  32. : this(writer, false)
  33. {
  34. }
  35. public PsdBlockLengthWriter(PsdBinaryWriter writer, bool hasLongLength)
  36. {
  37. this.writer = writer;
  38. this.hasLongLength = hasLongLength;
  39. // Store position so that we can return to it when the length is known.
  40. lengthPosition = writer.BaseStream.Position;
  41. // Write a sentinel value as a placeholder for the length.
  42. writer.Write((UInt32)0xFEEDFEED);
  43. if (hasLongLength)
  44. {
  45. writer.Write((UInt32)0xFEEDFEED);
  46. }
  47. // Store the start position of the data block so that we can calculate
  48. // its length when we're done writing.
  49. startPosition = writer.BaseStream.Position;
  50. }
  51. public void Write()
  52. {
  53. var endPosition = writer.BaseStream.Position;
  54. writer.BaseStream.Position = lengthPosition;
  55. long length = endPosition - startPosition;
  56. if (hasLongLength)
  57. {
  58. writer.Write(length);
  59. }
  60. else
  61. {
  62. writer.Write((UInt32)length);
  63. }
  64. writer.BaseStream.Position = endPosition;
  65. }
  66. public void Dispose()
  67. {
  68. if (!this.disposed)
  69. {
  70. Write();
  71. this.disposed = true;
  72. }
  73. }
  74. }
  75. }