Browse Source

Moar cleanup

Former-commit-id: 2768412a12ebae48de30635184a4e213d1033346
Former-commit-id: 033c6cc52ceec936e5c596f2dbe365d644d09a66
Former-commit-id: 7e94075a33f258c94fd9d1d06098c64f7ca7d783
af/merge-core
James Jackson-South 10 years ago
parent
commit
bf2ee4dd9b
  1. 4
      src/ImageProcessor/Formats/Gif/LzwDecoder.cs
  2. 65
      src/ImageProcessor/Formats/Png/Zlib/Adler32.cs
  3. 49
      src/ImageProcessor/Formats/Png/Zlib/Crc32.cs
  4. 7
      src/ImageProcessor/Formats/Png/Zlib/DeflateStrategy.cs
  5. 398
      src/ImageProcessor/Formats/Png/Zlib/Deflater.cs
  6. 106
      src/ImageProcessor/Formats/Png/Zlib/DeflaterConstants.cs
  7. 355
      src/ImageProcessor/Formats/Png/Zlib/DeflaterEngine.cs
  8. 679
      src/ImageProcessor/Formats/Png/Zlib/DeflaterHuffman.cs
  9. 581
      src/ImageProcessor/Formats/Png/Zlib/DeflaterOutputStream.cs
  10. 11
      src/ImageProcessor/Formats/Png/Zlib/DeflaterPending.cs
  11. 7
      src/ImageProcessor/Formats/Png/Zlib/GeneralBitFlags.cs
  12. 445
      src/ImageProcessor/Formats/Png/Zlib/Inflater.cs
  13. 46
      src/ImageProcessor/Formats/Png/Zlib/PendingBuffer.cs
  14. 2
      src/ImageProcessor/Formats/Png/Zlib/README.md
  15. 1
      src/ImageProcessor/ImageProcessor.csproj
  16. 1
      src/ImageProcessor/ImageProcessor.csproj.DotSettings
  17. 5
      tests/ImageProcessor.Tests/Processors/Formats/EncoderDecoderTests.cs

4
src/ImageProcessor/Formats/Gif/LzwDecoder.cs

@ -69,8 +69,8 @@ namespace ImageProcessor.Formats
int availableCode = clearCode + 2;
// Jillzhangs Code (Not From Me) see: http://giflib.codeplex.com/
// TODO: It's imperative that this close is cleaned up and commented properly.
// TODO: Unfortunately I can't figure out the character encoding to translate from the original Chinese.
// TODO: It's imperative that this code is cleaned up and commented properly.
// TODO: Unfortunately I can't figure out the character encoding to translate from the original Chinese.
int code; // ÓÃÓÚ´æ´¢µ±Ç°µÄ±àÂëÖµ
int oldCode = NullCode; // ÓÃÓÚ´æ´¢ÉÏÒ»´ÎµÄ±àÂëÖµ
int codeMask = (1 << codeSize) - 1; // ±íʾ±àÂëµÄ×î´óÖµ£¬Èç¹ûcodeSize=5,Ôòcode_mask=31

65
src/ImageProcessor/Formats/Png/Zlib/Adler32.cs

@ -1,4 +1,9 @@
namespace ImageProcessor.Formats
// <copyright file="Adler32.cs" company="James South">
// Copyright © James South and contributors.
// Licensed under the Apache License, Version 2.0.
// </copyright>
namespace ImageProcessor.Formats
{
using System;
@ -6,7 +11,8 @@
/// Computes Adler32 checksum for a stream of data. An Adler32
/// checksum is not as reliable as a CRC32 checksum, but a lot faster to
/// compute.
///
/// </summary>
/// <remarks>
/// The specification for Adler32 may be found in RFC 1950.
/// ZLIB Compressed Data Format Specification version 3.3)
///
@ -45,37 +51,34 @@
/// of the sequence part of s2, so that the length does not have to be
/// checked separately. (Any sequence of zeroes has a Fletcher
/// checksum of zero.)"
/// </summary>
/// <see cref="ICSharpCode.SharpZipLib.Zip.Compression.Streams.InflaterInputStream"/>
/// <see cref="ICSharpCode.SharpZipLib.Zip.Compression.Streams.DeflaterOutputStream"/>
/// </remarks>
/// <see cref="InflaterInputStream"/>
/// <see cref="DeflaterOutputStream"/>
public sealed class Adler32 : IChecksum
{
/// <summary>
/// largest prime smaller than 65536
/// </summary>
const uint BASE = 65521;
private const uint Base = 65521;
/// <summary>
/// Returns the Adler32 data checksum computed so far.
/// The checksum calculated to far.
/// </summary>
public long Value
{
get
{
return this.checksum;
}
}
private uint checksum;
/// <summary>
/// Initializes a new instance of the <see cref="Adler32"/> class.
/// Creates a new instance of the Adler32 class.
/// The checksum starts off with a value of 1.
/// Initializes a new instance of the <see cref="Adler32"/> class. The checksum starts off with a value of 1.
/// </summary>
public Adler32()
{
this.Reset();
}
/// <summary>
/// Returns the Adler32 data checksum computed so far.
/// </summary>
public long Value => this.checksum;
/// <summary>
/// Resets the Adler32 checksum to the initial value.
/// </summary>
@ -97,8 +100,8 @@
uint s1 = this.checksum & 0xFFFF;
uint s2 = this.checksum >> 16;
s1 = (s1 + ((uint)value & 0xFF)) % BASE;
s2 = (s1 + s2) % BASE;
s1 = (s1 + ((uint)value & 0xFF)) % Base;
s2 = (s1 + s2) % Base;
this.checksum = (s2 << 16) + s1;
}
@ -113,7 +116,7 @@
{
if (buffer == null)
{
throw new ArgumentNullException("buffer");
throw new ArgumentNullException(nameof(buffer));
}
this.Update(buffer, 0, buffer.Length);
@ -135,30 +138,30 @@
{
if (buffer == null)
{
throw new ArgumentNullException("buffer");
throw new ArgumentNullException(nameof(buffer));
}
if (offset < 0)
{
throw new ArgumentOutOfRangeException("offset", "cannot be negative");
throw new ArgumentOutOfRangeException(nameof(offset), "cannot be negative");
}
if (count < 0)
{
throw new ArgumentOutOfRangeException("count", "cannot be negative");
throw new ArgumentOutOfRangeException(nameof(count), "cannot be negative");
}
if (offset >= buffer.Length)
{
throw new ArgumentOutOfRangeException("offset", "not a valid index into buffer");
throw new ArgumentOutOfRangeException(nameof(offset), "not a valid index into buffer");
}
if (offset + count > buffer.Length)
{
throw new ArgumentOutOfRangeException("count", "exceeds buffer size");
throw new ArgumentOutOfRangeException(nameof(count), "exceeds buffer size");
}
//(By Per Bothner)
// (By Per Bothner)
uint s1 = this.checksum & 0xFFFF;
uint s2 = this.checksum >> 16;
@ -172,21 +175,19 @@
{
n = count;
}
count -= n;
while (--n >= 0)
{
s1 = s1 + (uint)(buffer[offset++] & 0xff);
s2 = s2 + s1;
}
s1 %= BASE;
s2 %= BASE;
s1 %= Base;
s2 %= Base;
}
this.checksum = (s2 << 16) | s1;
}
#region Instance Fields
uint checksum;
#endregion
}
}

49
src/ImageProcessor/Formats/Png/Zlib/Crc32.cs

@ -10,7 +10,8 @@ namespace ImageProcessor.Formats
/// <summary>
/// Generate a table for a byte-wise 32-bit CRC calculation on the polynomial:
/// x^32+x^26+x^23+x^22+x^16+x^12+x^11+x^10+x^8+x^7+x^5+x^4+x^2+x+1.
///
/// </summary>
/// <remarks>
/// Polynomials over GF(2) are represented in binary, one bit per coefficient,
/// with the lowest powers in the most significant bit. Then adding polynomials
/// is just exclusive-or, and multiplying a polynomial by x is a right shift by
@ -30,12 +31,19 @@ namespace ImageProcessor.Formats
/// The table is simply the CRC of all possible eight bit values. This is all
/// the information needed to generate CRC's on data a byte at a time for all
/// combinations of CRC register values and incoming bytes.
/// </summary>
/// </remarks>
public sealed class Crc32 : IChecksum
{
const uint CrcSeed = 0xFFFFFFFF;
/// <summary>
/// The crc seed
/// </summary>
private const uint CrcSeed = 0xFFFFFFFF;
readonly static uint[] CrcTable = new uint[] {
/// <summary>
/// The table of all possible eight bit values for fast lookup.
/// </summary>
private static readonly uint[] CrcTable =
{
0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419,
0x706AF48F, 0xE963A535, 0x9E6495A3, 0x0EDB8832, 0x79DCB8A4,
0xE0D5E91E, 0x97D2D988, 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07,
@ -90,15 +98,10 @@ namespace ImageProcessor.Formats
0x2D02EF8D
};
internal static uint ComputeCrc32(uint oldCrc, byte value)
{
return (uint)(Crc32.CrcTable[(oldCrc ^ value) & 0xFF] ^ (oldCrc >> 8));
}
/// <summary>
/// The crc data checksum so far.
/// </summary>
uint crc;
private uint crc;
/// <summary>
/// Returns the CRC32 data checksum computed so far.
@ -107,8 +110,9 @@ namespace ImageProcessor.Formats
{
get
{
return (long)this.crc;
return this.crc;
}
set
{
this.crc = (uint)value;
@ -126,9 +130,7 @@ namespace ImageProcessor.Formats
/// <summary>
/// Updates the checksum with the int bval.
/// </summary>
/// <param name = "value">
/// the byte is taken as the lower 8 bits of value
/// </param>
/// <param name="value">The byte is taken as the lower 8 bits of value.</param>
public void Update(int value)
{
this.crc ^= CrcSeed;
@ -146,7 +148,7 @@ namespace ImageProcessor.Formats
{
if (buffer == null)
{
throw new ArgumentNullException("buffer");
throw new ArgumentNullException(nameof(buffer));
}
this.Update(buffer, 0, buffer.Length);
@ -168,17 +170,17 @@ namespace ImageProcessor.Formats
{
if (buffer == null)
{
throw new ArgumentNullException("buffer");
throw new ArgumentNullException(nameof(buffer));
}
if (count < 0)
{
throw new ArgumentOutOfRangeException("count", "Count cannot be less than zero");
throw new ArgumentOutOfRangeException(nameof(count), "Count cannot be less than zero");
}
if (offset < 0 || offset + count > buffer.Length)
{
throw new ArgumentOutOfRangeException("offset");
throw new ArgumentOutOfRangeException(nameof(offset));
}
this.crc ^= CrcSeed;
@ -190,5 +192,16 @@ namespace ImageProcessor.Formats
this.crc ^= CrcSeed;
}
/// <summary>
/// Computes the crc value for the given byte.
/// </summary>
/// <param name="oldCrc">The previous value.</param>
/// <param name="value">The byte to compute against.</param>
/// <returns>The <see cref="uint"/></returns>
internal static uint ComputeCrc32(uint oldCrc, byte value)
{
return CrcTable[(oldCrc ^ value) & 0xFF] ^ (oldCrc >> 8);
}
}
}

7
src/ImageProcessor/Formats/Png/Zlib/DeflateStrategy.cs

@ -1,4 +1,9 @@
namespace ImageProcessor.Formats
// <copyright file="DeflateStrategy.cs" company="James South">
// Copyright © James South and contributors.
// Licensed under the Apache License, Version 2.0.
// </copyright>
namespace ImageProcessor.Formats
{
/// <summary>
/// Strategies for deflater

398
src/ImageProcessor/Formats/Png/Zlib/Deflater.cs

@ -1,9 +1,12 @@
namespace ImageProcessor.Formats
// <copyright file="Deflater.cs" company="James South">
// Copyright © James South and contributors.
// Licensed under the Apache License, Version 2.0.
// </copyright>
namespace ImageProcessor.Formats
{
using System;
//using ICSharpCode.SharpZipLib.Zip.Compression;
/// <summary>
/// This is the Deflater class. The deflater class compresses input
/// with the deflate algorithm described in RFC 1951. It has several
@ -11,12 +14,11 @@
///
/// This class is <i>not</i> thread safe. This is inherent in the API, due
/// to the split of deflate and setInput.
///
///
/// author of the original java version : Jochen Hoenicke
/// </summary>
public class Deflater
{
#region Deflater Documentation
/*
* The Deflater can do the following state transitions:
*
@ -51,149 +53,205 @@
* (7) At any time (7)
*
*/
#endregion
#region Public Constants
/// <summary>
/// The best and slowest compression level. This tries to find very
/// long and distant string repetitions.
/// </summary>
public const int BEST_COMPRESSION = 9;
public const int BestCompression = 9;
/// <summary>
/// The worst but fastest compression level.
/// </summary>
public const int BEST_SPEED = 1;
public const int BestSpeed = 1;
/// <summary>
/// The default compression level.
/// </summary>
public const int DEFAULT_COMPRESSION = -1;
public const int DefaultCompression = -1;
/// <summary>
/// This level won't compress at all but output uncompressed blocks.
/// </summary>
public const int NO_COMPRESSION = 0;
public const int NoCompression = 0;
/// <summary>
/// The compression method. This is the only method supported so far.
/// There is no need to use this constant at all.
/// </summary>
public const int DEFLATED = 8;
#endregion
#region Local Constants
private const int IS_SETDICT = 0x01;
private const int IS_FLUSHING = 0x04;
private const int IS_FINISHING = 0x08;
private const int INIT_STATE = 0x00;
private const int SETDICT_STATE = 0x01;
// private static int INIT_FINISHING_STATE = 0x08;
// private static int SETDICT_FINISHING_STATE = 0x09;
private const int BUSY_STATE = 0x10;
private const int FLUSHING_STATE = 0x14;
private const int FINISHING_STATE = 0x1c;
private const int FINISHED_STATE = 0x1e;
private const int CLOSED_STATE = 0x7f;
#endregion
#region Constructors
/// <summary>
/// Creates a new deflater with default compression level.
/// </summary>
public Deflater() : this(DEFAULT_COMPRESSION, false)
{
public const int Deflated = 8;
/// <summary>
/// The is dictionary set flag.
/// </summary>
private const int IsSetdict = 0x01;
/// <summary>
/// Flags whether flushing.
/// </summary>
private const int IsFlushing = 0x04;
/// <summary>
/// Flags whether finishing.
/// </summary>
private const int IsFinishing = 0x08;
/// <summary>
/// The initial stat flag
/// </summary>
private const int InitState = 0x00;
/// <summary>
/// Flags setting the dictionary.
/// </summary>
private const int SetdictState = 0x01;
/// <summary>
/// The busy state flag.
/// </summary>
private const int BusyState = 0x10;
/// <summary>
/// The flushing state flag.
/// </summary>
private const int FlushingState = 0x14;
/// <summary>
/// The finishing state flag.
/// </summary>
private const int FinishingState = 0x1c;
/// <summary>
/// The finished state flag.
/// </summary>
private const int FinishedState = 0x1e;
/// <summary>
/// The closed state flag.
/// </summary>
private const int ClosedState = 0x7f;
/// <summary>
/// The pending output.
/// </summary>
private readonly DeflaterPending pending;
/// <summary>
/// If true no Zlib/RFC1950 headers or footers are generated
/// </summary>
private readonly bool noZlibHeaderOrFooter;
/// <summary>
/// The deflater engine.
/// </summary>
private readonly DeflaterEngine engine;
/// <summary>
/// Compression level.
/// </summary>
private int deflaterLevel;
/// <summary>
/// The current state.
/// </summary>
private int state;
/// <summary>
/// The total bytes of output written.
/// </summary>
private long totalOut;
/// <summary>
/// Initializes a new instance of the <see cref="Deflater"/> class with the default compression level.
/// </summary>
public Deflater()
: this(DefaultCompression, false)
{
}
/// <summary>
/// Creates a new deflater with given compression level.
/// Initializes a new instance of the <see cref="Deflater"/> class with the given compressin level.
/// </summary>
/// <param name="level">
/// the compression level, a value between NO_COMPRESSION
/// and BEST_COMPRESSION, or DEFAULT_COMPRESSION.
/// The compression level, a value between NoCompression and BestCompression, or DefaultCompression.
/// </param>
/// <exception cref="System.ArgumentOutOfRangeException">if lvl is out of range.</exception>
public Deflater(int level) : this(level, false)
/// <exception cref="System.ArgumentOutOfRangeException">If level is out of range.</exception>
public Deflater(int level)
: this(level, false)
{
}
/// <summary>
/// Creates a new deflater with given compression level.
/// Initializes a new instance of the <see cref="Deflater"/> class with the given compressin level.
/// </summary>
/// <param name="level">
/// the compression level, a value between NO_COMPRESSION
/// and BEST_COMPRESSION.
/// The compression level, a value between NoCompression and BestCompression, or DefaultCompression.
/// </param>
/// <param name="noZlibHeaderOrFooter">
/// true, if we should suppress the Zlib/RFC1950 header at the
/// True, if we should suppress the Zlib/RFC1950 header at the
/// beginning and the adler checksum at the end of the output. This is
/// useful for the GZIP/PKZIP formats.
/// </param>
/// <exception cref="System.ArgumentOutOfRangeException">if lvl is out of range.</exception>
public Deflater(int level, bool noZlibHeaderOrFooter)
{
if (level == DEFAULT_COMPRESSION)
if (level == DefaultCompression)
{
level = 6;
}
else if (level < NO_COMPRESSION || level > BEST_COMPRESSION)
else if (level < NoCompression || level > BestCompression)
{
throw new ArgumentOutOfRangeException("level");
throw new ArgumentOutOfRangeException(nameof(level));
}
pending = new DeflaterPending();
engine = new DeflaterEngine(pending);
this.pending = new DeflaterPending();
this.engine = new DeflaterEngine(this.pending);
this.noZlibHeaderOrFooter = noZlibHeaderOrFooter;
SetStrategy(DeflateStrategy.Default);
SetLevel(level);
Reset();
}
#endregion
/// <summary>
/// Resets the deflater. The deflater acts afterwards as if it was
/// just created with the same compression level and strategy as it
/// had before.
/// </summary>
public void Reset()
{
state = (noZlibHeaderOrFooter ? BUSY_STATE : INIT_STATE);
totalOut = 0;
pending.Reset();
engine.Reset();
this.SetStrategy(DeflateStrategy.Default);
this.SetLevel(level);
this.Reset();
}
/// <summary>
/// Gets the current adler checksum of the data that was processed so far.
/// </summary>
public int Adler
{
get
{
return engine.Adler;
}
}
public int Adler => this.engine.Adler;
/// <summary>
/// Gets the number of input bytes processed so far.
/// </summary>
public long TotalIn
{
get
{
return engine.TotalIn;
}
}
public long TotalIn => this.engine.TotalIn;
/// <summary>
/// Gets the number of output bytes so far.
/// </summary>
public long TotalOut
public long TotalOut => this.totalOut;
/// <summary>
/// Returns true if the stream was finished and no more output bytes
/// are available.
/// </summary>
public bool IsFinished => (this.state == FinishedState) && this.pending.IsFlushed;
/// <summary>
/// Returns true, if the input buffer is empty.
/// You should then call setInput().
/// NOTE: This method can also return true when the stream
/// was finished.
/// </summary>
public bool IsNeedingInput => this.engine.NeedsInput();
/// <summary>
/// Resets the deflater. The deflater acts afterwards as if it was
/// just created with the same compression level and strategy as it
/// had before.
/// </summary>
public void Reset()
{
get
{
return totalOut;
}
this.state = this.noZlibHeaderOrFooter ? BusyState : InitState;
this.totalOut = 0;
this.pending.Reset();
this.engine.Reset();
}
/// <summary>
@ -205,7 +263,7 @@
/// </summary>
public void Flush()
{
state |= IS_FLUSHING;
this.state |= IsFlushing;
}
/// <summary>
@ -215,33 +273,7 @@
/// </summary>
public void Finish()
{
state |= (IS_FLUSHING | IS_FINISHING);
}
/// <summary>
/// Returns true if the stream was finished and no more output bytes
/// are available.
/// </summary>
public bool IsFinished
{
get
{
return (state == FINISHED_STATE) && pending.IsFlushed;
}
}
/// <summary>
/// Returns true, if the input buffer is empty.
/// You should then call setInput().
/// NOTE: This method can also return true when the stream
/// was finished.
/// </summary>
public bool IsNeedingInput
{
get
{
return engine.NeedsInput();
}
this.state |= IsFlushing | IsFinishing;
}
/// <summary>
@ -261,7 +293,7 @@
/// </exception>
public void SetInput(byte[] input)
{
SetInput(input, 0, input.Length);
this.SetInput(input, 0, input.Length);
}
/// <summary>
@ -284,11 +316,12 @@
/// </exception>
public void SetInput(byte[] input, int offset, int count)
{
if ((state & IS_FINISHING) != 0)
if ((this.state & IsFinishing) != 0)
{
throw new InvalidOperationException("Finish() already called");
}
engine.SetInput(input, offset, count);
this.engine.SetInput(input, offset, count);
}
/// <summary>
@ -302,19 +335,19 @@
/// </param>
public void SetLevel(int level)
{
if (level == DEFAULT_COMPRESSION)
if (level == DefaultCompression)
{
level = 6;
}
else if (level < NO_COMPRESSION || level > BEST_COMPRESSION)
else if (level < NoCompression || level > BestCompression)
{
throw new ArgumentOutOfRangeException("level");
throw new ArgumentOutOfRangeException(nameof(level));
}
if (this.level != level)
if (this.deflaterLevel != level)
{
this.level = level;
engine.SetLevel(level);
this.deflaterLevel = level;
this.engine.SetLevel(level);
}
}
@ -324,7 +357,7 @@
/// <returns>Returns the current compression level</returns>
public int GetLevel()
{
return level;
return this.deflaterLevel;
}
/// <summary>
@ -338,7 +371,7 @@
/// </param>
public void SetStrategy(DeflateStrategy strategy)
{
engine.Strategy = strategy;
this.engine.Strategy = strategy;
}
/// <summary>
@ -353,7 +386,7 @@
/// </returns>
public int Deflate(byte[] output)
{
return Deflate(output, 0, output.Length);
return this.Deflate(output, 0, output.Length);
}
/// <summary>
@ -382,95 +415,100 @@
{
int origLength = length;
if (state == CLOSED_STATE)
if (this.state == ClosedState)
{
throw new InvalidOperationException("Deflater closed");
}
if (state < BUSY_STATE)
if (this.state < BusyState)
{
// output header
int header = (DEFLATED +
((DeflaterConstants.MAX_WBITS - 8) << 4)) << 8;
int level_flags = (level - 1) >> 1;
if (level_flags < 0 || level_flags > 3)
int header = (Deflated +
((DeflaterConstants.MaxWbits - 8) << 4)) << 8;
int levelFlags = (this.deflaterLevel - 1) >> 1;
if (levelFlags < 0 || levelFlags > 3)
{
level_flags = 3;
levelFlags = 3;
}
header |= level_flags << 6;
if ((state & IS_SETDICT) != 0)
header |= levelFlags << 6;
if ((this.state & IsSetdict) != 0)
{
// Dictionary was set
header |= DeflaterConstants.PRESET_DICT;
header |= DeflaterConstants.PresetDict;
}
header += 31 - (header % 31);
pending.WriteShortMSB(header);
if ((state & IS_SETDICT) != 0)
this.pending.WriteShortMSB(header);
if ((this.state & IsSetdict) != 0)
{
int chksum = engine.Adler;
engine.ResetAdler();
pending.WriteShortMSB(chksum >> 16);
pending.WriteShortMSB(chksum & 0xffff);
int chksum = this.engine.Adler;
this.engine.ResetAdler();
this.pending.WriteShortMSB(chksum >> 16);
this.pending.WriteShortMSB(chksum & 0xffff);
}
state = BUSY_STATE | (state & (IS_FLUSHING | IS_FINISHING));
this.state = BusyState | (this.state & (IsFlushing | IsFinishing));
}
for (;;)
for (; ;)
{
int count = pending.Flush(output, offset, length);
int count = this.pending.Flush(output, offset, length);
offset += count;
totalOut += count;
this.totalOut += count;
length -= count;
if (length == 0 || state == FINISHED_STATE)
if (length == 0 || this.state == FinishedState)
{
break;
}
if (!engine.Deflate((state & IS_FLUSHING) != 0, (state & IS_FINISHING) != 0))
if (!this.engine.Deflate((this.state & IsFlushing) != 0, (this.state & IsFinishing) != 0))
{
if (state == BUSY_STATE)
if (this.state == BusyState)
{
// We need more input now
return origLength - length;
}
else if (state == FLUSHING_STATE)
else if (this.state == FlushingState)
{
if (level != NO_COMPRESSION)
if (this.deflaterLevel != NoCompression)
{
/* We have to supply some lookahead. 8 bit lookahead
* is needed by the zlib inflater, and we must fill
* the next byte, so that all bits are flushed.
*/
int neededbits = 8 + ((-pending.BitCount) & 7);
int neededbits = 8 + ((-this.pending.BitCount) & 7);
while (neededbits > 0)
{
/* write a static tree block consisting solely of
* an EOF:
*/
pending.WriteBits(2, 10);
this.pending.WriteBits(2, 10);
neededbits -= 10;
}
}
state = BUSY_STATE;
this.state = BusyState;
}
else if (state == FINISHING_STATE)
else if (this.state == FinishingState)
{
pending.AlignToByte();
this.pending.AlignToByte();
// Compressed data is complete. Write footer information if required.
if (!noZlibHeaderOrFooter)
if (!this.noZlibHeaderOrFooter)
{
int adler = engine.Adler;
pending.WriteShortMSB(adler >> 16);
pending.WriteShortMSB(adler & 0xffff);
int adler = this.engine.Adler;
this.pending.WriteShortMSB(adler >> 16);
this.pending.WriteShortMSB(adler & 0xffff);
}
state = FINISHED_STATE;
this.state = FinishedState;
}
}
}
return origLength - length;
}
@ -486,7 +524,7 @@
/// </exception>
public void SetDictionary(byte[] dictionary)
{
SetDictionary(dictionary, 0, dictionary.Length);
this.SetDictionary(dictionary, 0, dictionary.Length);
}
/// <summary>
@ -511,45 +549,13 @@
/// </exception>
public void SetDictionary(byte[] dictionary, int index, int count)
{
if (state != INIT_STATE)
if (this.state != InitState)
{
throw new InvalidOperationException();
}
state = SETDICT_STATE;
engine.SetDictionary(dictionary, index, count);
this.state = SetdictState;
this.engine.SetDictionary(dictionary, index, count);
}
#region Instance Fields
/// <summary>
/// Compression level.
/// </summary>
int level;
/// <summary>
/// If true no Zlib/RFC1950 headers or footers are generated
/// </summary>
bool noZlibHeaderOrFooter;
/// <summary>
/// The current state.
/// </summary>
int state;
/// <summary>
/// The total bytes of output written.
/// </summary>
long totalOut;
/// <summary>
/// The pending output.
/// </summary>
DeflaterPending pending;
/// <summary>
/// The deflater engine.
/// </summary>
DeflaterEngine engine;
#endregion
}
}

106
src/ImageProcessor/Formats/Png/Zlib/DeflaterConstants.cs

@ -1,4 +1,9 @@
namespace ImageProcessor.Formats
// <copyright file="DeflaterConstants.cs" company="James South">
// Copyright © James South and contributors.
// Licensed under the Apache License, Version 2.0.
// </copyright>
namespace ImageProcessor.Formats
{
using System;
@ -7,139 +12,134 @@
/// </summary>
public class DeflaterConstants
{
/// <summary>
/// Set to true to enable debugging
/// </summary>
public const bool DEBUGGING = false;
/// <summary>
/// Written to Zip file to identify a stored block
/// </summary>
public const int STORED_BLOCK = 0;
public const int StoredBlock = 0;
/// <summary>
/// Identifies static tree in Zip file
/// </summary>
public const int STATIC_TREES = 1;
public const int StaticTrees = 1;
/// <summary>
/// Identifies dynamic tree in Zip file
/// </summary>
public const int DYN_TREES = 2;
public const int DynTrees = 2;
/// <summary>
/// Header flag indicating a preset dictionary for deflation
/// </summary>
public const int PRESET_DICT = 0x20;
public const int PresetDict = 0x20;
/// <summary>
/// Sets internal buffer sizes for Huffman encoding
/// </summary>
public const int DEFAULT_MEM_LEVEL = 8;
public const int DefaultMemLevel = 8;
/// <summary>
/// Internal compression engine constant
/// </summary>
public const int MAX_MATCH = 258;
/// </summary>
public const int MaxMatch = 258;
/// <summary>
/// Internal compression engine constant
/// </summary>
public const int MIN_MATCH = 3;
/// </summary>
public const int MinMatch = 3;
/// <summary>
/// Internal compression engine constant
/// </summary>
public const int MAX_WBITS = 15;
/// </summary>
public const int MaxWbits = 15;
/// <summary>
/// Internal compression engine constant
/// </summary>
public const int WSIZE = 1 << MAX_WBITS;
/// </summary>
public const int Wsize = 1 << MaxWbits;
/// <summary>
/// Internal compression engine constant
/// </summary>
public const int WMASK = WSIZE - 1;
/// </summary>
public const int Wmask = Wsize - 1;
/// <summary>
/// Internal compression engine constant
/// </summary>
public const int HASH_BITS = DEFAULT_MEM_LEVEL + 7;
/// </summary>
public const int HashBits = DefaultMemLevel + 7;
/// <summary>
/// Internal compression engine constant
/// </summary>
public const int HASH_SIZE = 1 << HASH_BITS;
/// </summary>
public const int HashSize = 1 << HashBits;
/// <summary>
/// Internal compression engine constant
/// </summary>
public const int HASH_MASK = HASH_SIZE - 1;
/// </summary>
public const int HashMask = HashSize - 1;
/// <summary>
/// Internal compression engine constant
/// </summary>
public const int HASH_SHIFT = (HASH_BITS + MIN_MATCH - 1) / MIN_MATCH;
/// </summary>
public const int HashShift = (HashBits + MinMatch - 1) / MinMatch;
/// <summary>
/// Internal compression engine constant
/// </summary>
public const int MIN_LOOKAHEAD = MAX_MATCH + MIN_MATCH + 1;
/// </summary>
public const int MinLookahead = MaxMatch + MinMatch + 1;
/// <summary>
/// Internal compression engine constant
/// </summary>
public const int MAX_DIST = WSIZE - MIN_LOOKAHEAD;
/// </summary>
public const int MaxDist = Wsize - MinLookahead;
/// <summary>
/// Internal compression engine constant
/// </summary>
public const int PENDING_BUF_SIZE = 1 << (DEFAULT_MEM_LEVEL + 8);
/// </summary>
public const int PendingBufSize = 1 << (DefaultMemLevel + 8);
/// <summary>
/// Internal compression engine constant
/// </summary>
public static int MAX_BLOCK_SIZE = Math.Min(65535, PENDING_BUF_SIZE - 5);
/// </summary>
public const int Deflatestored = 0;
/// <summary>
/// Internal compression engine constant
/// </summary>
public const int DEFLATE_STORED = 0;
/// </summary>
public const int Deflatefast = 1;
/// <summary>
/// Internal compression engine constant
/// </summary>
public const int DEFLATE_FAST = 1;
/// </summary>
public const int Deflateslow = 2;
/// <summary>
/// Internal compression engine constant
/// </summary>
public const int DEFLATE_SLOW = 2;
/// </summary>
public static int MaxBlockSize => Math.Min(65535, PendingBufSize - 5);
/// <summary>
/// Internal compression engine constant
/// </summary>
public static int[] GOOD_LENGTH = { 0, 4, 4, 4, 4, 8, 8, 8, 32, 32 };
/// </summary>
public static int[] GoodLength => new[] { 0, 4, 4, 4, 4, 8, 8, 8, 32, 32 };
/// <summary>
/// Internal compression engine constant
/// </summary>
public static int[] MAX_LAZY = { 0, 4, 5, 6, 4, 16, 16, 32, 128, 258 };
/// </summary>
public static int[] MaxLazy => new[] { 0, 4, 5, 6, 4, 16, 16, 32, 128, 258 };
/// <summary>
/// Internal compression engine constant
/// </summary>
public static int[] NICE_LENGTH = { 0, 8, 16, 32, 16, 32, 128, 128, 258, 258 };
/// </summary>
public static int[] NiceLength => new[] { 0, 8, 16, 32, 16, 32, 128, 128, 258, 258 };
/// <summary>
/// Internal compression engine constant
/// </summary>
public static int[] MAX_CHAIN = { 0, 4, 8, 32, 16, 32, 128, 256, 1024, 4096 };
/// </summary>
public static int[] MaxChain => new[] { 0, 4, 8, 32, 16, 32, 128, 256, 1024, 4096 };
/// <summary>
/// Internal compression engine constant
/// </summary>
public static int[] COMPR_FUNC = { 0, 1, 1, 1, 1, 2, 2, 2, 2, 2 };
/// </summary>
public static int[] ComprFunc => new[] { 0, 1, 1, 1, 1, 2, 2, 2, 2, 2 };
}
}

355
src/ImageProcessor/Formats/Png/Zlib/DeflaterEngine.cs

@ -1,4 +1,9 @@
namespace ImageProcessor.Formats
// <copyright file="DeflaterEngine.cs" company="James South">
// Copyright © James South and contributors.
// Licensed under the Apache License, Version 2.0.
// </copyright>
namespace ImageProcessor.Formats
{
using System;
@ -22,7 +27,7 @@
public class DeflaterEngine : DeflaterConstants
{
/// <summary>
/// ne more than the maximum upper bounds.
/// One more than the maximum upper bounds.
/// </summary>
private const int TooFar = 4096;
@ -43,11 +48,110 @@
/// </summary>
private readonly short[] head;
/// <summary>
/// This array contains the part of the uncompressed stream that
/// is of relevance. The current character is indexed by strstart.
/// </summary>
private readonly byte[] window;
/// <summary>
/// Stores the pending output of the deflator
/// </summary>
private readonly DeflaterPending pending;
/// <summary>
/// The huffman deflator
/// </summary>
private readonly DeflaterHuffman huffman;
/// <summary>
/// The adler checksum
/// </summary>
private readonly Adler32 adler;
/// <summary>
/// Hash index of string to be inserted.
/// </summary>
private int insertHashIndex;
/// <summary>
/// Index of the beginning of a match.
/// </summary>
private int matchStart;
/// <summary>
/// Length of best match
/// </summary>
private int matchLen;
/// <summary>
/// Set if previous match exists
/// </summary>
private bool prevAvailable;
/// <summary>
/// The index of the beinning of a block
/// </summary>
private int blockStart;
/// <summary>
/// Points to the current character in the window.
/// </summary>
private int strstart;
/// <summary>
/// lookahead is the number of characters starting at strstart in
/// window that are valid.
/// So window[strstart] until window[strstart+lookahead-1] are valid
/// characters.
/// </summary>
private int lookahead;
/// <summary>
/// The maximum chain length
/// </summary>
private int maxChain;
/// <summary>
/// The maximum lazy length
/// </summary>
private int maxLazy;
/// <summary>
/// The nice length
/// </summary>
private int niceLength;
/// <summary>
/// The good length
/// </summary>
private int goodLength;
/// <summary>
/// The current compression function.
/// </summary>
private int compressionFunction;
/// <summary>
/// The input data for compression.
/// </summary>
private byte[] inputBuf;
/// <summary>
/// The total bytes of input read.
/// </summary>
private long totalIn;
/// <summary>
/// The offset into inputBuf, where input data starts.
/// </summary>
private int inputOff;
/// <summary>
/// The end offset of the input data.
/// </summary>
private int inputEnd;
/// <summary>
/// Initializes a new instance of the <see cref="DeflaterEngine"/> class with a pending buffer.
/// </summary>
@ -58,9 +162,9 @@
this.huffman = new DeflaterHuffman(pending);
this.adler = new Adler32();
this.window = new byte[2 * WSIZE];
this.head = new short[HASH_SIZE];
this.previousIndex = new short[WSIZE];
this.window = new byte[2 * Wsize];
this.head = new short[HashSize];
this.previousIndex = new short[Wsize];
// We start at index 1, to avoid an implementation deficiency, that
// we cannot build a repeat pattern at index 0.
@ -98,13 +202,13 @@
switch (this.compressionFunction)
{
case DEFLATE_STORED:
case Deflatestored:
progress = this.DeflateStored(canFlush, finish);
break;
case DEFLATE_FAST:
case Deflatefast:
progress = this.DeflateFast(canFlush, finish);
break;
case DEFLATE_SLOW:
case Deflateslow:
progress = this.DeflateSlow(canFlush, finish);
break;
default:
@ -176,15 +280,15 @@
public void SetDictionary(byte[] buffer, int offset, int length)
{
this.adler.Update(buffer, offset, length);
if (length < MIN_MATCH)
if (length < MinMatch)
{
return;
}
if (length > MAX_DIST)
if (length > MaxDist)
{
offset += length - MAX_DIST;
length = MAX_DIST;
offset += length - MaxDist;
length = MaxDist;
}
Array.Copy(buffer, offset, this.window, this.strstart, length);
@ -212,14 +316,14 @@
this.lookahead = 0;
this.totalIn = 0;
this.prevAvailable = false;
this.matchLen = MIN_MATCH - 1;
this.matchLen = MinMatch - 1;
for (int i = 0; i < HASH_SIZE; i++)
for (int i = 0; i < HashSize; i++)
{
this.head[i] = 0;
}
for (int i = 0; i < WSIZE; i++)
for (int i = 0; i < Wsize; i++)
{
this.previousIndex[i] = 0;
}
@ -244,16 +348,16 @@
throw new ArgumentOutOfRangeException(nameof(level));
}
this.goodLength = GOOD_LENGTH[level];
this.maxLazy = MAX_LAZY[level];
this.niceLength = NICE_LENGTH[level];
this.maxChain = MAX_CHAIN[level];
this.goodLength = GoodLength[level];
this.maxLazy = MaxLazy[level];
this.niceLength = NiceLength[level];
this.maxChain = MaxChain[level];
if (COMPR_FUNC[level] != this.compressionFunction)
if (ComprFunc[level] != this.compressionFunction)
{
switch (this.compressionFunction)
{
case DEFLATE_STORED:
case Deflatestored:
if (this.strstart > this.blockStart)
{
this.huffman.FlushStoredBlock(this.window, this.blockStart, this.strstart - this.blockStart, false);
@ -263,17 +367,16 @@
this.UpdateHash();
break;
case DEFLATE_FAST:
case Deflatefast:
if (this.strstart > this.blockStart)
{
this.huffman.FlushBlock(this.window, this.blockStart, this.strstart - this.blockStart,
false);
this.huffman.FlushBlock(this.window, this.blockStart, this.strstart - this.blockStart, false);
this.blockStart = this.strstart;
}
break;
case DEFLATE_SLOW:
case Deflateslow:
if (this.prevAvailable)
{
this.huffman.TallyLit(this.window[this.strstart - 1] & 0xff);
@ -286,31 +389,31 @@
}
this.prevAvailable = false;
this.matchLen = MIN_MATCH - 1;
this.matchLen = MinMatch - 1;
break;
}
this.compressionFunction = COMPR_FUNC[level];
this.compressionFunction = ComprFunc[level];
}
}
/// <summary>
/// Fill the window
/// Fills the window
/// </summary>
public void FillWindow()
{
// If the window is almost full and there is insufficient lookahead,
// move the upper half to the lower one to make room in the upper half.
if (this.strstart >= WSIZE + MAX_DIST)
if (this.strstart >= Wsize + MaxDist)
{
this.SlideWindow();
}
// If there is not enough lookahead, but still some input left,
// read in the input
while (this.lookahead < MIN_LOOKAHEAD && this.inputOff < this.inputEnd)
while (this.lookahead < MinLookahead && this.inputOff < this.inputEnd)
{
int more = (2 * WSIZE) - this.lookahead - this.strstart;
int more = (2 * Wsize) - this.lookahead - this.strstart;
if (more > this.inputEnd - this.inputOff)
{
@ -325,15 +428,18 @@
this.lookahead += more;
}
if (this.lookahead >= MIN_MATCH)
if (this.lookahead >= MinMatch)
{
this.UpdateHash();
}
}
/// <summary>
/// Updates this hash.
/// </summary>
private void UpdateHash()
{
this.insertHashIndex = (this.window[this.strstart] << HASH_SHIFT) ^ this.window[this.strstart + 1];
this.insertHashIndex = (this.window[this.strstart] << HashShift) ^ this.window[this.strstart + 1];
}
/// <summary>
@ -344,34 +450,37 @@
private int InsertString()
{
short match;
int hash = ((this.insertHashIndex << HASH_SHIFT) ^ this.window[this.strstart + (MIN_MATCH - 1)]) & HASH_MASK;
int hash = ((this.insertHashIndex << HashShift) ^ this.window[this.strstart + (MinMatch - 1)]) & HashMask;
this.previousIndex[this.strstart & WMASK] = match = this.head[hash];
this.previousIndex[this.strstart & Wmask] = match = this.head[hash];
this.head[hash] = unchecked((short)this.strstart);
this.insertHashIndex = hash;
return match & 0xffff;
}
/// <summary>
/// Slides the current byte window to the ewlefvent part of the uncompressed stream.
/// </summary>
private void SlideWindow()
{
Array.Copy(this.window, WSIZE, this.window, 0, WSIZE);
this.matchStart -= WSIZE;
this.strstart -= WSIZE;
this.blockStart -= WSIZE;
Array.Copy(this.window, Wsize, this.window, 0, Wsize);
this.matchStart -= Wsize;
this.strstart -= Wsize;
this.blockStart -= Wsize;
// Slide the hash table (could be avoided with 32 bit values
// at the expense of memory usage).
for (int i = 0; i < HASH_SIZE; ++i)
for (int i = 0; i < HashSize; ++i)
{
int m = this.head[i] & 0xffff;
this.head[i] = (short)(m >= WSIZE ? (m - WSIZE) : 0);
this.head[i] = (short)(m >= Wsize ? (m - Wsize) : 0);
}
// Slide the prev table.
for (int i = 0; i < WSIZE; i++)
for (int i = 0; i < Wsize; i++)
{
int m = this.previousIndex[i] & 0xffff;
this.previousIndex[i] = (short)(m >= WSIZE ? (m - WSIZE) : 0);
this.previousIndex[i] = (short)(m >= Wsize ? (m - Wsize) : 0);
}
}
@ -392,11 +501,11 @@
short[] previous = this.previousIndex;
int scan = this.strstart;
int bestEnd = this.strstart + this.matchLen;
int bestLength = Math.Max(this.matchLen, MIN_MATCH - 1);
int bestLength = Math.Max(this.matchLen, MinMatch - 1);
int limit = Math.Max(this.strstart - MAX_DIST, 0);
int limit = Math.Max(this.strstart - MaxDist, 0);
int strend = this.strstart + MAX_MATCH - 1;
int strend = this.strstart + MaxMatch - 1;
byte scanEnd1 = this.window[bestEnd - 1];
byte scanEnd = this.window[bestEnd];
@ -458,12 +567,19 @@
}
scan = this.strstart;
} while ((curMatch = previous[curMatch & WMASK] & 0xffff) > limit && --chainLength != 0);
}
while ((curMatch = previous[curMatch & Wmask] & 0xffff) > limit && --chainLength != 0);
this.matchLen = Math.Min(bestLength, this.lookahead);
return this.matchLen >= MIN_MATCH;
return this.matchLen >= MinMatch;
}
/// <summary>
/// Returns a value indicating whether the uncompressed block is stored.
/// </summary>
/// <param name="flush">Whether to flush the stream.</param>
/// <param name="finish">Whether to finish the stream.</param>
/// <returns>The <see cref="bool"/></returns>
private bool DeflateStored(bool flush, bool finish)
{
if (!flush && (this.lookahead == 0))
@ -476,14 +592,14 @@
int storedLength = this.strstart - this.blockStart;
if ((storedLength >= MAX_BLOCK_SIZE) || // Block is full
(this.blockStart < WSIZE && storedLength >= MAX_DIST) || // Block may move out of window
if ((storedLength >= MaxBlockSize) || // Block is full
(this.blockStart < Wsize && storedLength >= MaxDist) || // Block may move out of window
flush)
{
bool lastBlock = finish;
if (storedLength > MAX_BLOCK_SIZE)
if (storedLength > MaxBlockSize)
{
storedLength = MAX_BLOCK_SIZE;
storedLength = MaxBlockSize;
lastBlock = false;
}
@ -495,14 +611,20 @@
return true;
}
/// <summary>
/// Performs a fast deflation of the input stream return a value to indicate succes.
/// </summary>
/// <param name="flush">Whether to flush the stream.</param>
/// <param name="finish">Whether to finish the stream.</param>
/// <returns>The <see cref="bool"/></returns>
private bool DeflateFast(bool flush, bool finish)
{
if (this.lookahead < MIN_LOOKAHEAD && !flush)
if (this.lookahead < MinLookahead && !flush)
{
return false;
}
while (this.lookahead >= MIN_LOOKAHEAD || flush)
while (this.lookahead >= MinLookahead || flush)
{
if (this.lookahead == 0)
{
@ -512,27 +634,26 @@
return false;
}
if (this.strstart > (2 * WSIZE) - MIN_LOOKAHEAD)
if (this.strstart > (2 * Wsize) - MinLookahead)
{
/* slide window, as FindLongestMatch needs this.
* This should only happen when flushing and the window
* is almost full.
*/
// slide window, as FindLongestMatch needs this.
// This should only happen when flushing and the window
// is almost full.
this.SlideWindow();
}
int hashHead;
if (this.lookahead >= MIN_MATCH &&
if (this.lookahead >= MinMatch &&
(hashHead = this.InsertString()) != 0 &&
this.Strategy != DeflateStrategy.HuffmanOnly &&
this.strstart - hashHead <= MAX_DIST &&
this.strstart - hashHead <= MaxDist &&
this.FindLongestMatch(hashHead))
{
// longestMatch sets matchStart and matchLen
bool full = this.huffman.TallyDist(this.strstart - this.matchStart, this.matchLen);
this.lookahead -= this.matchLen;
if (this.matchLen <= this.maxLazy && this.lookahead >= MIN_MATCH)
if (this.matchLen <= this.maxLazy && this.lookahead >= MinMatch)
{
while (--this.matchLen > 0)
{
@ -545,13 +666,13 @@
else
{
this.strstart += this.matchLen;
if (this.lookahead >= MIN_MATCH - 1)
if (this.lookahead >= MinMatch - 1)
{
this.UpdateHash();
}
}
this.matchLen = MIN_MATCH - 1;
this.matchLen = MinMatch - 1;
if (!full)
{
continue;
@ -577,14 +698,20 @@
return true;
}
/// <summary>
/// Performs a slow deflation of the input stream return a value to indicate succes.
/// </summary>
/// <param name="flush">Whether to flush the stream.</param>
/// <param name="finish">Whether to finish the stream.</param>
/// <returns>The <see cref="bool"/></returns>
private bool DeflateSlow(bool flush, bool finish)
{
if (this.lookahead < MIN_LOOKAHEAD && !flush)
if (this.lookahead < MinLookahead && !flush)
{
return false;
}
while (this.lookahead >= MIN_LOOKAHEAD || flush)
while (this.lookahead >= MinLookahead || flush)
{
if (this.lookahead == 0)
{
@ -596,13 +723,12 @@
this.prevAvailable = false;
// We are flushing everything
this.huffman.FlushBlock(this.window, this.blockStart, this.strstart - this.blockStart,
finish);
this.huffman.FlushBlock(this.window, this.blockStart, this.strstart - this.blockStart, finish);
this.blockStart = this.strstart;
return false;
}
if (this.strstart >= (2 * WSIZE) - MIN_LOOKAHEAD)
if (this.strstart >= (2 * Wsize) - MinLookahead)
{
// slide window, as FindLongestMatch needs this.
// This should only happen when flushing and the window
@ -612,29 +738,26 @@
int prevMatch = this.matchStart;
int prevLen = this.matchLen;
if (this.lookahead >= MIN_MATCH)
if (this.lookahead >= MinMatch)
{
int hashHead = this.InsertString();
if (this.Strategy != DeflateStrategy.HuffmanOnly &&
hashHead != 0 &&
this.strstart - hashHead <= MAX_DIST &&
this.strstart - hashHead <= MaxDist &&
this.FindLongestMatch(hashHead))
{
// longestMatch sets matchStart and matchLen
// Discard match if too small and too far away
if (this.matchLen <= 5 && (this.Strategy == DeflateStrategy.Filtered || (this.matchLen == MIN_MATCH && this.strstart - this.matchStart > TooFar)))
if (this.matchLen <= 5 && (this.Strategy == DeflateStrategy.Filtered || (this.matchLen == MinMatch && this.strstart - this.matchStart > TooFar)))
{
this.matchLen = MIN_MATCH - 1;
this.matchLen = MinMatch - 1;
}
}
}
// previous match was better
if ((prevLen >= MIN_MATCH) && (this.matchLen <= prevLen))
if ((prevLen >= MinMatch) && (this.matchLen <= prevLen))
{
this.huffman.TallyDist(this.strstart - 1 - prevMatch, prevLen);
prevLen -= 2;
@ -642,16 +765,17 @@
{
this.strstart++;
this.lookahead--;
if (this.lookahead >= MIN_MATCH)
if (this.lookahead >= MinMatch)
{
this.InsertString();
}
} while (--prevLen > 0);
}
while (--prevLen > 0);
this.strstart++;
this.lookahead--;
this.prevAvailable = false;
this.matchLen = MIN_MATCH - 1;
this.matchLen = MinMatch - 1;
}
else
{
@ -682,76 +806,5 @@
return true;
}
private int matchStart;
// Length of best match
private int matchLen;
// Set if previous match exists
private bool prevAvailable;
private int blockStart;
/// <summary>
/// Points to the current character in the window.
/// </summary>
private int strstart;
/// <summary>
/// lookahead is the number of characters starting at strstart in
/// window that are valid.
/// So window[strstart] until window[strstart+lookahead-1] are valid
/// characters.
/// </summary>
private int lookahead;
/// <summary>
/// This array contains the part of the uncompressed stream that
/// is of relevance. The current character is indexed by strstart.
/// </summary>
private byte[] window;
private int maxChain;
private int maxLazy;
private int niceLength;
private int goodLength;
/// <summary>
/// The current compression function.
/// </summary>
private int compressionFunction;
/// <summary>
/// The input data for compression.
/// </summary>
private byte[] inputBuf;
/// <summary>
/// The total bytes of input read.
/// </summary>
private long totalIn;
/// <summary>
/// The offset into inputBuf, where input data starts.
/// </summary>
private int inputOff;
/// <summary>
/// The end offset of the input data.
/// </summary>
private int inputEnd;
private DeflaterPending pending;
private DeflaterHuffman huffman;
/// <summary>
/// The adler checksum
/// </summary>
private Adler32 adler;
}
}

679
src/ImageProcessor/Formats/Png/Zlib/DeflaterHuffman.cs

File diff suppressed because it is too large

581
src/ImageProcessor/Formats/Png/Zlib/DeflaterOutputStream.cs

@ -1,4 +1,9 @@
namespace ImageProcessor.Formats
// <copyright file="DeflaterOutputStream.cs" company="James South">
// Copyright © James South and contributors.
// Licensed under the Apache License, Version 2.0.
// </copyright>
namespace ImageProcessor.Formats
{
using System;
using System.IO;
@ -6,13 +11,49 @@
/// <summary>
/// A special stream deflating or compressing the bytes that are
/// written to it. It uses a Deflater to perform actual deflating.<br/>
/// Authors of the original java version : Tom Tromey, Jochen Hoenicke
/// Authors of the original java version : Tom Tromey, Jochen Hoenicke
/// </summary>
public class DeflaterOutputStream : Stream
{
#region Constructors
/// <summary>
/// Creates a new DeflaterOutputStream with a default Deflater and default buffer size.
/// The deflater which is used to deflate the stream.
/// </summary>
private readonly Deflater deflater;
/// <summary>
/// Base stream the deflater depends on.
/// </summary>
private readonly Stream baseOutputStream;
/// <summary>
/// This buffer is used temporarily to retrieve the bytes from the
/// deflater and write them to the underlying output stream.
/// </summary>
private readonly byte[] bytebuffer;
/// <summary>
/// The password
/// </summary>
private string password;
/// <summary>
/// The keys
/// </summary>
private uint[] keys;
/// <summary>
/// Whether the stream is closed
/// </summary>
private bool isClosed;
/// <summary>
/// Whether dispose should close the underlying stream.
/// </summary>
private bool isStreamOwner = true;
/// <summary>
/// Initializes a new instance of the <see cref="DeflaterOutputStream"/> class
/// with a default Deflater and default buffer size.
/// </summary>
/// <param name="baseOutputStream">
/// the output stream where deflated output should be written.
@ -23,8 +64,8 @@
}
/// <summary>
/// Creates a new DeflaterOutputStream with the given Deflater and
/// default buffer size.
/// Initializes a new instance of the <see cref="DeflaterOutputStream"/> class
/// with the given Deflater and default buffer size.
/// </summary>
/// <param name="baseOutputStream">
/// the output stream where deflated output should be written.
@ -38,8 +79,8 @@
}
/// <summary>
/// Creates a new DeflaterOutputStream with the given Deflater and
/// buffer size.
/// Initializes a new instance of the <see cref="DeflaterOutputStream"/> class
/// with the given Deflater and buffer size.
/// </summary>
/// <param name="baseOutputStream">
/// The output stream where deflated output is written.
@ -50,80 +91,34 @@
/// <param name="bufferSize">
/// The buffer size in bytes to use when deflating (minimum value 512)
/// </param>
/// <exception cref="ArgumentOutOfRangeException">
/// bufsize is less than or equal to zero.
/// </exception>
/// <exception cref="ArgumentException">
/// baseOutputStream does not support writing
/// </exception>
/// <exception cref="ArgumentNullException">
/// deflater instance is null
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">buffersize is less than or equal to zero.</exception>
/// <exception cref="ArgumentException">baseOutputStream does not support writing.</exception>
/// <exception cref="ArgumentNullException">deflater instance is null.</exception>
public DeflaterOutputStream(Stream baseOutputStream, Deflater deflater, int bufferSize)
{
if (baseOutputStream == null)
{
throw new ArgumentNullException("baseOutputStream");
throw new ArgumentNullException(nameof(baseOutputStream));
}
if (baseOutputStream.CanWrite == false)
{
throw new ArgumentException("Must support writing", "baseOutputStream");
throw new ArgumentException("Must support writing", nameof(baseOutputStream));
}
if (deflater == null)
{
throw new ArgumentNullException("deflater");
throw new ArgumentNullException(nameof(deflater));
}
if (bufferSize < 512)
{
throw new ArgumentOutOfRangeException("bufferSize");
throw new ArgumentOutOfRangeException(nameof(bufferSize));
}
baseOutputStream_ = baseOutputStream;
buffer_ = new byte[bufferSize];
deflater_ = deflater;
}
#endregion
#region Public API
/// <summary>
/// Finishes the stream by calling finish() on the deflater.
/// </summary>
/// <exception cref="ImageFormatException">
/// Not all input is deflated
/// </exception>
public virtual void Finish()
{
deflater_.Finish();
while (!deflater_.IsFinished)
{
int len = deflater_.Deflate(buffer_, 0, buffer_.Length);
if (len <= 0)
{
break;
}
if (keys != null)
{
EncryptBlock(buffer_, 0, len);
}
baseOutputStream_.Write(buffer_, 0, len);
}
if (!deflater_.IsFinished)
{
throw new ImageFormatException("Can't deflate all input?");
}
baseOutputStream_.Flush();
if (keys != null)
{
keys = null;
}
this.baseOutputStream = baseOutputStream;
this.bytebuffer = new byte[bufferSize];
this.deflater = deflater;
}
/// <summary>
@ -132,28 +127,14 @@
/// </summary>
public bool IsStreamOwner
{
get { return isStreamOwner_; }
set { isStreamOwner_ = value; }
get { return this.isStreamOwner; }
set { this.isStreamOwner = value; }
}
/// <summary>
/// <summary>
/// Allows client to determine if an entry can be patched after its added
/// </summary>
public bool CanPatchEntries
{
get
{
return baseOutputStream_.CanSeek;
}
}
#endregion
#region Encryption
string password;
uint[] keys;
public bool CanPatchEntries => this.baseOutputStream.CanSeek;
/// <summary>
/// Get/set the password used for encryption.
@ -163,189 +144,42 @@
{
get
{
return password;
return this.password;
}
set
{
if ((value != null) && (value.Length == 0))
{
password = null;
this.password = null;
}
else
{
password = value;
}
}
}
/// <summary>
/// Encrypt a block of data
/// </summary>
/// <param name="buffer">
/// Data to encrypt. NOTE the original contents of the buffer are lost
/// </param>
/// <param name="offset">
/// Offset of first byte in buffer to encrypt
/// </param>
/// <param name="length">
/// Number of bytes in buffer to encrypt
/// </param>
protected void EncryptBlock(byte[] buffer, int offset, int length)
{
for (int i = offset; i < offset + length; ++i)
{
byte oldbyte = buffer[i];
buffer[i] ^= EncryptByte();
UpdateKeys(oldbyte);
}
}
/// <summary>
/// Initializes encryption keys based on given <paramref name="password"/>.
/// </summary>
/// <param name="password">The password.</param>
protected void InitializePassword(string password)
{
keys = new uint[] {
0x12345678,
0x23456789,
0x34567890
};
byte[] rawPassword = ZipConstants.ConvertToArray(password);
for (int i = 0; i < rawPassword.Length; ++i)
{
UpdateKeys((byte)rawPassword[i]);
}
}
#if !NET_1_1 && !NETCF_2_0 && !NOCRYPTO
/// <summary>
/// Initializes encryption keys based on given password.
/// </summary>
protected void InitializeAESPassword(ZipEntry entry, string rawPassword,
out byte[] salt, out byte[] pwdVerifier) {
salt = new byte[entry.AESSaltLen];
// Salt needs to be cryptographically random, and unique per file
if (_aesRnd == null)
_aesRnd = new RNGCryptoServiceProvider();
_aesRnd.GetBytes(salt);
int blockSize = entry.AESKeySize / 8; // bits to bytes
cryptoTransform_ = new ZipAESTransform(rawPassword, salt, blockSize, true);
pwdVerifier = ((ZipAESTransform)cryptoTransform_).PwdVerifier;
}
#endif
#if NETCF_1_0 || NOCRYPTO
/// <summary>
/// Encrypt a single byte
/// </summary>
/// <returns>
/// The encrypted value
/// </returns>
protected byte EncryptByte()
{
uint temp = ((keys[2] & 0xFFFF) | 2);
return (byte)((temp * (temp ^ 1)) >> 8);
}
/// <summary>
/// Update encryption keys
/// </summary>
protected void UpdateKeys(byte ch)
{
keys[0] = Crc32.ComputeCrc32(keys[0], ch);
keys[1] = keys[1] + (byte)keys[0];
keys[1] = keys[1] * 134775813 + 1;
keys[2] = Crc32.ComputeCrc32(keys[2], (byte)(keys[1] >> 24));
}
#endif
#endregion
#region Deflation Support
/// <summary>
/// Deflates everything in the input buffers. This will call
/// <code>def.deflate()</code> until all bytes from the input buffers
/// are processed.
/// </summary>
protected void Deflate()
{
while (!deflater_.IsNeedingInput)
{
int deflateCount = deflater_.Deflate(buffer_, 0, buffer_.Length);
if (deflateCount <= 0)
{
break;
}
#if NETCF_1_0 || NOCRYPTO
if (keys != null)
#else
if (cryptoTransform_ != null)
#endif
{
EncryptBlock(buffer_, 0, deflateCount);
this.password = value;
}
baseOutputStream_.Write(buffer_, 0, deflateCount);
}
if (!deflater_.IsNeedingInput)
{
throw new ImageFormatException("DeflaterOutputStream can't deflate all input?");
}
}
#endregion
#region Stream Overrides
/// <summary>
/// Gets value indicating stream can be read from
/// </summary>
public override bool CanRead
{
get
{
return false;
}
}
public override bool CanRead => false;
/// <summary>
/// Gets a value indicating if seeking is supported for this stream
/// This property always returns false
/// </summary>
public override bool CanSeek
{
get
{
return false;
}
}
public override bool CanSeek => false;
/// <summary>
/// Get value indicating if this stream supports writing
/// </summary>
public override bool CanWrite
{
get
{
return baseOutputStream_.CanWrite;
}
}
public override bool CanWrite => this.baseOutputStream.CanWrite;
/// <summary>
/// Get current length of stream
/// </summary>
public override long Length
{
get
{
return baseOutputStream_.Length;
}
}
public override long Length => this.baseOutputStream.Length;
/// <summary>
/// Gets the current position within the stream.
@ -355,14 +189,49 @@
{
get
{
return baseOutputStream_.Position;
return this.baseOutputStream.Position;
}
set
{
throw new NotSupportedException("Position property not supported");
}
}
/// <summary>
/// Finishes the stream by calling finish() on the deflater.
/// </summary>
/// <exception cref="ImageFormatException">
/// Not all input is deflated
/// </exception>
public virtual void Finish()
{
this.deflater.Finish();
while (!this.deflater.IsFinished)
{
int len = this.deflater.Deflate(this.bytebuffer, 0, this.bytebuffer.Length);
if (len <= 0)
{
break;
}
if (this.keys != null)
{
this.EncryptBlock(this.bytebuffer, 0, len);
}
this.baseOutputStream.Write(this.bytebuffer, 0, len);
}
if (!this.deflater.IsFinished)
{
throw new ImageFormatException("Can't deflate all input?");
}
this.baseOutputStream.Flush();
this.keys = null;
}
/// <summary>
/// Sets the current position of this stream to the given value. Not supported by this class!
/// </summary>
@ -407,109 +276,16 @@
{
throw new NotSupportedException("DeflaterOutputStream Read not supported");
}
#if !PCL
/// <summary>
/// Asynchronous reads are not supported a NotSupportedException is always thrown
/// </summary>
/// <param name="buffer">The buffer to read into.</param>
/// <param name="offset">The offset to start storing data at.</param>
/// <param name="count">The number of bytes to read</param>
/// <param name="callback">The async callback to use.</param>
/// <param name="state">The state to use.</param>
/// <returns>Returns an <see cref="IAsyncResult"/></returns>
/// <exception cref="NotSupportedException">Any access</exception>
public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
{
throw new NotSupportedException("DeflaterOutputStream BeginRead not currently supported");
}
/// <summary>
/// Asynchronous writes arent supported, a NotSupportedException is always thrown
/// </summary>
/// <param name="buffer">The buffer to write.</param>
/// <param name="offset">The offset to begin writing at.</param>
/// <param name="count">The number of bytes to write.</param>
/// <param name="callback">The <see cref="AsyncCallback"/> to use.</param>
/// <param name="state">The state object.</param>
/// <returns>Returns an IAsyncResult.</returns>
/// <exception cref="NotSupportedException">Any access</exception>
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
{
throw new NotSupportedException("BeginWrite is not supported");
}
#endif
/// <summary>
/// Flushes the stream by calling <see cref="DeflaterOutputStream.Flush">Flush</see> on the deflater and then
/// on the underlying stream. This ensures that all bytes are flushed.
/// </summary>
public override void Flush()
{
deflater_.Flush();
Deflate();
baseOutputStream_.Flush();
}
/// <summary>
/// Calls <see cref="Finish"/> and closes the underlying
/// stream when <see cref="IsStreamOwner"></see> is true.
/// </summary>
#if !PCL
public override void Close()
{
if (!isClosed_)
{
isClosed_ = true;
try {
Finish();
#if NETCF_1_0 || NOCRYPTO
keys =null;
#else
if ( cryptoTransform_ != null ) {
GetAuthCodeIfAES();
cryptoTransform_.Dispose();
cryptoTransform_ = null;
}
#endif
}
finally {
if( isStreamOwner_ ) {
baseOutputStream_.Close();
}
}
}
}
#else
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if (disposing && !isClosed_)
{
isClosed_ = true;
try
{
Finish();
keys = null;
}
finally
{
if (isStreamOwner_)
{
baseOutputStream_.Dispose();
}
}
}
}
#endif
private void GetAuthCodeIfAES()
{
#if !NET_1_1 && !NETCF_2_0 && !NOCRYPTO
if (cryptoTransform_ is ZipAESTransform) {
AESAuthCode = ((ZipAESTransform)cryptoTransform_).GetAuthCode();
}
#endif
this.deflater.Flush();
this.Deflate();
this.baseOutputStream.Flush();
}
/// <summary>
@ -522,7 +298,7 @@
{
byte[] b = new byte[1];
b[0] = value;
Write(b, 0, 1);
this.Write(b, 0, 1);
}
/// <summary>
@ -539,39 +315,132 @@
/// </param>
public override void Write(byte[] buffer, int offset, int count)
{
deflater_.SetInput(buffer, offset, count);
Deflate();
this.deflater.SetInput(buffer, offset, count);
this.Deflate();
}
#endregion
#region Instance Fields
/// <summary>
/// This buffer is used temporarily to retrieve the bytes from the
/// deflater and write them to the underlying output stream.
/// Encrypt a block of data
/// </summary>
/// <param name="buffer">
/// Data to encrypt. NOTE the original contents of the buffer are lost
/// </param>
/// <param name="offset">
/// Offset of first byte in buffer to encrypt
/// </param>
/// <param name="length">
/// Number of bytes in buffer to encrypt
/// </param>
protected void EncryptBlock(byte[] buffer, int offset, int length)
{
for (int i = offset; i < offset + length; ++i)
{
byte oldbyte = buffer[i];
buffer[i] ^= this.EncryptByte();
this.UpdateKeys(oldbyte);
}
}
/// <summary>
/// Initializes encryption keys based on given <paramref name="pssword"/>.
/// </summary>
byte[] buffer_;
/// <param name="pssword">The password.</param>
protected void InitializePassword(string pssword)
{
this.keys = new uint[]
{
0x12345678,
0x23456789,
0x34567890
};
byte[] rawPassword = ZipConstants.ConvertToArray(pssword);
foreach (byte b in rawPassword)
{
this.UpdateKeys(b);
}
}
/// <summary>
/// The deflater which is used to deflate the stream.
/// Encrypt a single byte
/// </summary>
protected Deflater deflater_;
/// <returns>
/// The encrypted value
/// </returns>
protected byte EncryptByte()
{
uint temp = (this.keys[2] & 0xFFFF) | 2;
return (byte)((temp * (temp ^ 1)) >> 8);
}
/// <summary>
/// Base stream the deflater depends on.
/// Update encryption keys
/// </summary>
protected Stream baseOutputStream_;
/// <param name="ch">The character.</param>
protected void UpdateKeys(byte ch)
{
this.keys[0] = Crc32.ComputeCrc32(this.keys[0], ch);
this.keys[1] = this.keys[1] + (byte)this.keys[0];
this.keys[1] = (this.keys[1] * 134775813) + 1;
this.keys[2] = Crc32.ComputeCrc32(this.keys[2], (byte)(this.keys[1] >> 24));
}
bool isClosed_;
/// <summary>
/// Deflates everything in the input buffers. This will call
/// <code>def.deflate()</code> until all bytes from the input buffers
/// are processed.
/// </summary>
protected void Deflate()
{
while (!this.deflater.IsNeedingInput)
{
int deflateCount = this.deflater.Deflate(this.bytebuffer, 0, this.bytebuffer.Length);
bool isStreamOwner_ = true;
#endregion
if (deflateCount <= 0)
{
break;
}
if (this.keys != null)
{
this.EncryptBlock(this.bytebuffer, 0, deflateCount);
}
#region Static Fields
this.baseOutputStream.Write(this.bytebuffer, 0, deflateCount);
}
if (!this.deflater.IsNeedingInput)
{
throw new ImageFormatException("DeflaterOutputStream can't deflate all input?");
}
}
/// <summary>
/// Calls <see cref="Finish"/> and closes the underlying
/// stream when <see cref="IsStreamOwner"></see> is true.
/// </summary>
/// <param name="disposing">If true, the object gets disposed.</param>
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if (disposing && !this.isClosed)
{
this.isClosed = true;
#if !NET_1_1 && !NETCF_2_0 && !NOCRYPTO
// Static to help ensure that multiple files within a zip will get different random salt
private static RNGCryptoServiceProvider _aesRnd;
#endif
#endregion
try
{
this.Finish();
this.keys = null;
}
finally
{
if (this.isStreamOwner)
{
this.baseOutputStream.Dispose();
}
}
}
}
}
}

11
src/ImageProcessor/Formats/Png/Zlib/DeflaterPending.cs

@ -1,8 +1,13 @@
namespace ImageProcessor.Formats
// <copyright file="DeflaterPending.cs" company="James South">
// Copyright © James South and contributors.
// Licensed under the Apache License, Version 2.0.
// </copyright>
namespace ImageProcessor.Formats
{
/// <summary>
/// This class stores the pending output of the Deflater.
///
///
/// author of the original java version : Jochen Hoenicke
/// </summary>
public class DeflaterPending : PendingBuffer
@ -12,7 +17,7 @@
/// Construct instance with default buffer size
/// </summary>
public DeflaterPending()
: base(DeflaterConstants.PENDING_BUF_SIZE)
: base(DeflaterConstants.PendingBufSize)
{
}
}

7
src/ImageProcessor/Formats/Png/Zlib/GeneralBitFlags.cs

@ -1,4 +1,9 @@
namespace ImageProcessor.Formats
// <copyright file="GeneralBitFlags.cs" company="James South">
// Copyright © James South and contributors.
// Licensed under the Apache License, Version 2.0.
// </copyright>
namespace ImageProcessor.Formats
{
using System;

445
src/ImageProcessor/Formats/Png/Zlib/Inflater.cs

@ -1,10 +1,11 @@
namespace ImageProcessor.Formats {
namespace ImageProcessor.Formats
{
using System;
/// <summary>
/// Inflater is used to decompress data that has been compressed according
/// to the "deflate" standard described in rfc1951.
///
///
/// By default Zlib (rfc1950) headers and footers are expected in the input.
/// You can use constructor <code> public Inflater(bool noHeader)</code> passing true
/// if there is no Zlib header information
@ -28,19 +29,20 @@
/// </summary>
public class Inflater
{
#region Constants/Readonly
/// <summary>
/// Copy lengths for literal codes 257..285
/// </summary>
static readonly int[] CPLENS = {
3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258
};
private static readonly int[] CPLENS =
{
3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258
};
/// <summary>
/// Extra bits for literal codes 257..285
/// </summary>
static readonly int[] CPLEXT = {
private static readonly int[] CPLEXT =
{
0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2,
3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0
};
@ -48,7 +50,8 @@
/// <summary>
/// Copy offsets for distance codes 0..29
/// </summary>
static readonly int[] CPDIST = {
private static readonly int[] CPDIST =
{
1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
8193, 12289, 16385, 24577
@ -57,7 +60,8 @@
/// <summary>
/// Extra bits for distance codes
/// </summary>
static readonly int[] CPDEXT = {
private static readonly int[] CPDEXT =
{
0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6,
7, 7, 8, 8, 9, 9, 10, 10, 11, 11,
12, 12, 13, 13
@ -66,95 +70,92 @@
/// <summary>
/// These are the possible states for an inflater
/// </summary>
const int DECODE_HEADER = 0;
const int DECODE_DICT = 1;
const int DECODE_BLOCKS = 2;
const int DECODE_STORED_LEN1 = 3;
const int DECODE_STORED_LEN2 = 4;
const int DECODE_STORED = 5;
const int DECODE_DYN_HEADER = 6;
const int DECODE_HUFFMAN = 7;
const int DECODE_HUFFMAN_LENBITS = 8;
const int DECODE_HUFFMAN_DIST = 9;
const int DECODE_HUFFMAN_DISTBITS = 10;
const int DECODE_CHKSUM = 11;
const int FINISHED = 12;
#endregion
#region Instance Fields
private const int DECODE_HEADER = 0;
private const int DECODE_DICT = 1;
private const int DECODE_BLOCKS = 2;
private const int DECODE_STORED_LEN1 = 3;
private const int DECODE_STORED_LEN2 = 4;
private const int DECODE_STORED = 5;
private const int DECODE_DYN_HEADER = 6;
private const int DECODE_HUFFMAN = 7;
private const int DECODE_HUFFMAN_LENBITS = 8;
private const int DECODE_HUFFMAN_DIST = 9;
private const int DECODE_HUFFMAN_DISTBITS = 10;
private const int DECODE_CHKSUM = 11;
private const int FINISHED = 12;
/// <summary>
/// This variable contains the current state.
/// </summary>
int mode;
private int mode;
/// <summary>
/// The adler checksum of the dictionary or of the decompressed
/// stream, as it is written in the header resp. footer of the
/// compressed stream.
/// compressed stream.
/// Only valid if mode is DECODE_DICT or DECODE_CHKSUM.
/// </summary>
int readAdler;
private int readAdler;
/// <summary>
/// The number of bits needed to complete the current state. This
/// is valid, if mode is DECODE_DICT, DECODE_CHKSUM,
/// DECODE_HUFFMAN_LENBITS or DECODE_HUFFMAN_DISTBITS.
/// </summary>
int neededBits;
int repLength;
int repDist;
int uncomprLen;
private int neededBits;
private int repLength;
private int repDist;
private int uncomprLen;
/// <summary>
/// True, if the last block flag was set in the last block of the
/// inflated stream. This means that the stream ends after the
/// current block.
/// </summary>
bool isLastBlock;
private bool isLastBlock;
/// <summary>
/// The total number of inflated bytes.
/// </summary>
long totalOut;
private long totalOut;
/// <summary>
/// The total number of bytes set with setInput(). This is not the
/// value returned by the TotalIn property, since this also includes the
/// unprocessed input.
/// </summary>
long totalIn;
private long totalIn;
/// <summary>
/// This variable stores the noHeader flag that was given to the constructor.
/// True means, that the inflated stream doesn't contain a Zlib header or
/// True means, that the inflated stream doesn't contain a Zlib header or
/// footer.
/// </summary>
bool noHeader;
private bool noHeader;
StreamManipulator input;
OutputWindow outputWindow;
InflaterDynHeader dynHeader;
InflaterHuffmanTree litlenTree, distTree;
Adler32 adler;
#endregion
private StreamManipulator input;
private OutputWindow outputWindow;
private InflaterDynHeader dynHeader;
private InflaterHuffmanTree litlenTree, distTree;
private Adler32 adler;
#region Constructors
/// <summary>
/// Creates a new inflater or RFC1951 decompressor
/// Initializes a new instance of the <see cref="Inflater"/> class.
/// RFC1950/Zlib headers and footers will be expected in the input data
/// </summary>
public Inflater() : this(false)
public Inflater()
: this(false)
{
}
/// <summary>
/// Creates a new inflater.
/// Initializes a new instance of the <see cref="Inflater"/> class.
/// </summary>
/// <param name="noHeader">
/// True if no RFC1950/Zlib header and footer fields are expected in the input data
///
///
/// This is used for GZIPed/Zipped input.
///
///
/// For compatibility with
/// Sun JDK you should provide one byte of input more than needed in
/// this case.
@ -163,11 +164,10 @@
{
this.noHeader = noHeader;
this.adler = new Adler32();
input = new StreamManipulator();
outputWindow = new OutputWindow();
mode = noHeader ? DECODE_BLOCKS : DECODE_HEADER;
this.input = new StreamManipulator();
this.outputWindow = new OutputWindow();
this.mode = noHeader ? DECODE_BLOCKS : DECODE_HEADER;
}
#endregion
/// <summary>
/// Resets the inflater so that a new stream can be decompressed. All
@ -175,16 +175,16 @@
/// </summary>
public void Reset()
{
mode = noHeader ? DECODE_BLOCKS : DECODE_HEADER;
totalIn = 0;
totalOut = 0;
input.Reset();
outputWindow.Reset();
dynHeader = null;
litlenTree = null;
distTree = null;
isLastBlock = false;
adler.Reset();
this.mode = this.noHeader ? DECODE_BLOCKS : DECODE_HEADER;
this.totalIn = 0;
this.totalOut = 0;
this.input.Reset();
this.outputWindow.Reset();
this.dynHeader = null;
this.litlenTree = null;
this.distTree = null;
this.isLastBlock = false;
this.adler.Reset();
}
/// <summary>
@ -198,12 +198,13 @@
/// </exception>
private bool DecodeHeader()
{
int header = input.PeekBits(16);
int header = this.input.PeekBits(16);
if (header < 0)
{
return false;
}
input.DropBits(16);
this.input.DropBits(16);
// The header is written in "wrong" byte order
header = ((header << 8) | (header >> 8)) & 0xffff;
@ -212,27 +213,28 @@
throw new ImageFormatException("Header checksum illegal");
}
if ((header & 0x0f00) != (Deflater.DEFLATED << 8))
if ((header & 0x0f00) != (Deflater.Deflated << 8))
{
throw new ImageFormatException("Compression Method unknown");
}
/* Maximum size of the backwards window in bits.
* We currently ignore this, but we could use it to make the
* inflater window more space efficient. On the other hand the
* full window (15 bits) is needed most times, anyway.
int max_wbits = ((header & 0x7000) >> 12) + 8;
*/
* We currently ignore this, but we could use it to make the
* inflater window more space efficient. On the other hand the
* full window (15 bits) is needed most times, anyway.
int max_wbits = ((header & 0x7000) >> 12) + 8;
*/
if ((header & 0x0020) == 0)
{ // Dictionary flag?
mode = DECODE_BLOCKS;
this.mode = DECODE_BLOCKS;
}
else
{
mode = DECODE_DICT;
neededBits = 32;
this.mode = DECODE_DICT;
this.neededBits = 32;
}
return true;
}
@ -244,17 +246,19 @@
/// </returns>
private bool DecodeDict()
{
while (neededBits > 0)
while (this.neededBits > 0)
{
int dictByte = input.PeekBits(8);
int dictByte = this.input.PeekBits(8);
if (dictByte < 0)
{
return false;
}
input.DropBits(8);
readAdler = (readAdler << 8) | dictByte;
neededBits -= 8;
this.input.DropBits(8);
this.readAdler = (this.readAdler << 8) | dictByte;
this.neededBits -= 8;
}
return false;
}
@ -270,17 +274,17 @@
/// </exception>
private bool DecodeHuffman()
{
int free = outputWindow.GetFreeSpace();
int free = this.outputWindow.GetFreeSpace();
while (free >= 258)
{
int symbol;
switch (mode)
switch (this.mode)
{
case DECODE_HUFFMAN:
// This is the inner loop so it is optimized a bit
while (((symbol = litlenTree.GetSymbol(input)) & ~0xff) == 0)
while (((symbol = this.litlenTree.GetSymbol(this.input)) & ~0xff) == 0)
{
outputWindow.Write(symbol);
this.outputWindow.Write(symbol);
if (--free < 258)
{
return true;
@ -296,41 +300,44 @@
else
{
// symbol == 256: end of block
distTree = null;
litlenTree = null;
mode = DECODE_BLOCKS;
this.distTree = null;
this.litlenTree = null;
this.mode = DECODE_BLOCKS;
return true;
}
}
try
{
repLength = CPLENS[symbol - 257];
neededBits = CPLEXT[symbol - 257];
this.repLength = CPLENS[symbol - 257];
this.neededBits = CPLEXT[symbol - 257];
}
catch (Exception)
{
throw new ImageFormatException("Illegal rep length code");
}
goto case DECODE_HUFFMAN_LENBITS; // fall through
case DECODE_HUFFMAN_LENBITS:
if (neededBits > 0)
if (this.neededBits > 0)
{
mode = DECODE_HUFFMAN_LENBITS;
int i = input.PeekBits(neededBits);
this.mode = DECODE_HUFFMAN_LENBITS;
int i = this.input.PeekBits(this.neededBits);
if (i < 0)
{
return false;
}
input.DropBits(neededBits);
repLength += i;
this.input.DropBits(this.neededBits);
this.repLength += i;
}
mode = DECODE_HUFFMAN_DIST;
this.mode = DECODE_HUFFMAN_DIST;
goto case DECODE_HUFFMAN_DIST; // fall through
case DECODE_HUFFMAN_DIST:
symbol = distTree.GetSymbol(input);
symbol = this.distTree.GetSymbol(this.input);
if (symbol < 0)
{
return false;
@ -338,8 +345,8 @@
try
{
repDist = CPDIST[symbol];
neededBits = CPDEXT[symbol];
this.repDist = CPDIST[symbol];
this.neededBits = CPDEXT[symbol];
}
catch (Exception)
{
@ -349,27 +356,29 @@
goto case DECODE_HUFFMAN_DISTBITS; // fall through
case DECODE_HUFFMAN_DISTBITS:
if (neededBits > 0)
if (this.neededBits > 0)
{
mode = DECODE_HUFFMAN_DISTBITS;
int i = input.PeekBits(neededBits);
this.mode = DECODE_HUFFMAN_DISTBITS;
int i = this.input.PeekBits(this.neededBits);
if (i < 0)
{
return false;
}
input.DropBits(neededBits);
repDist += i;
this.input.DropBits(this.neededBits);
this.repDist += i;
}
outputWindow.Repeat(repLength, repDist);
free -= repLength;
mode = DECODE_HUFFMAN;
this.outputWindow.Repeat(this.repLength, this.repDist);
free -= this.repLength;
this.mode = DECODE_HUFFMAN;
break;
default:
throw new ImageFormatException("Inflater unknown mode");
}
}
return true;
}
@ -384,24 +393,25 @@
/// </exception>
private bool DecodeChksum()
{
while (neededBits > 0)
while (this.neededBits > 0)
{
int chkByte = input.PeekBits(8);
int chkByte = this.input.PeekBits(8);
if (chkByte < 0)
{
return false;
}
input.DropBits(8);
readAdler = (readAdler << 8) | chkByte;
neededBits -= 8;
this.input.DropBits(8);
this.readAdler = (this.readAdler << 8) | chkByte;
this.neededBits -= 8;
}
if ((int)adler.Value != readAdler)
if ((int)this.adler.Value != this.readAdler)
{
throw new ImageFormatException("Adler chksum doesn't match: " + (int)adler.Value + " vs. " + readAdler);
throw new ImageFormatException("Adler chksum doesn't match: " + (int)this.adler.Value + " vs. " + this.readAdler);
}
mode = FINISHED;
this.mode = FINISHED;
return false;
}
@ -416,120 +426,129 @@
/// </exception>
private bool Decode()
{
switch (mode)
switch (this.mode)
{
case DECODE_HEADER:
return DecodeHeader();
return this.DecodeHeader();
case DECODE_DICT:
return DecodeDict();
return this.DecodeDict();
case DECODE_CHKSUM:
return DecodeChksum();
return this.DecodeChksum();
case DECODE_BLOCKS:
if (isLastBlock)
if (this.isLastBlock)
{
if (noHeader)
if (this.noHeader)
{
mode = FINISHED;
this.mode = FINISHED;
return false;
}
else
{
input.SkipToByteBoundary();
neededBits = 32;
mode = DECODE_CHKSUM;
this.input.SkipToByteBoundary();
this.neededBits = 32;
this.mode = DECODE_CHKSUM;
return true;
}
}
int type = input.PeekBits(3);
int type = this.input.PeekBits(3);
if (type < 0)
{
return false;
}
input.DropBits(3);
this.input.DropBits(3);
if ((type & 1) != 0)
{
isLastBlock = true;
this.isLastBlock = true;
}
switch (type >> 1)
{
case DeflaterConstants.STORED_BLOCK:
input.SkipToByteBoundary();
mode = DECODE_STORED_LEN1;
case DeflaterConstants.StoredBlock:
this.input.SkipToByteBoundary();
this.mode = DECODE_STORED_LEN1;
break;
case DeflaterConstants.STATIC_TREES:
litlenTree = InflaterHuffmanTree.defLitLenTree;
distTree = InflaterHuffmanTree.defDistTree;
mode = DECODE_HUFFMAN;
case DeflaterConstants.StaticTrees:
this.litlenTree = InflaterHuffmanTree.defLitLenTree;
this.distTree = InflaterHuffmanTree.defDistTree;
this.mode = DECODE_HUFFMAN;
break;
case DeflaterConstants.DYN_TREES:
dynHeader = new InflaterDynHeader();
mode = DECODE_DYN_HEADER;
case DeflaterConstants.DynTrees:
this.dynHeader = new InflaterDynHeader();
this.mode = DECODE_DYN_HEADER;
break;
default:
throw new ImageFormatException("Unknown block type " + type);
}
return true;
case DECODE_STORED_LEN1:
{
if ((uncomprLen = input.PeekBits(16)) < 0)
if ((this.uncomprLen = this.input.PeekBits(16)) < 0)
{
return false;
}
input.DropBits(16);
mode = DECODE_STORED_LEN2;
this.input.DropBits(16);
this.mode = DECODE_STORED_LEN2;
}
goto case DECODE_STORED_LEN2; // fall through
case DECODE_STORED_LEN2:
{
int nlen = input.PeekBits(16);
int nlen = this.input.PeekBits(16);
if (nlen < 0)
{
return false;
}
input.DropBits(16);
if (nlen != (uncomprLen ^ 0xffff))
this.input.DropBits(16);
if (nlen != (this.uncomprLen ^ 0xffff))
{
throw new ImageFormatException("broken uncompressed block");
}
mode = DECODE_STORED;
this.mode = DECODE_STORED;
}
goto case DECODE_STORED; // fall through
case DECODE_STORED:
{
int more = outputWindow.CopyStored(input, uncomprLen);
uncomprLen -= more;
if (uncomprLen == 0)
int more = this.outputWindow.CopyStored(this.input, this.uncomprLen);
this.uncomprLen -= more;
if (this.uncomprLen == 0)
{
mode = DECODE_BLOCKS;
this.mode = DECODE_BLOCKS;
return true;
}
return !input.IsNeedingInput;
return !this.input.IsNeedingInput;
}
case DECODE_DYN_HEADER:
if (!dynHeader.Decode(input))
if (!this.dynHeader.Decode(this.input))
{
return false;
}
litlenTree = dynHeader.BuildLitLenTree();
distTree = dynHeader.BuildDistTree();
mode = DECODE_HUFFMAN;
this.litlenTree = this.dynHeader.BuildLitLenTree();
this.distTree = this.dynHeader.BuildDistTree();
this.mode = DECODE_HUFFMAN;
goto case DECODE_HUFFMAN; // fall through
case DECODE_HUFFMAN:
case DECODE_HUFFMAN_LENBITS:
case DECODE_HUFFMAN_DIST:
case DECODE_HUFFMAN_DISTBITS:
return DecodeHuffman();
return this.DecodeHuffman();
case FINISHED:
return false;
@ -550,7 +569,7 @@
/// </param>
public void SetDictionary(byte[] buffer)
{
SetDictionary(buffer, 0, buffer.Length);
this.SetDictionary(buffer, 0, buffer.Length);
}
/// <summary>
@ -591,20 +610,21 @@
throw new ArgumentOutOfRangeException(nameof(count));
}
if (!IsNeedingDictionary)
if (!this.IsNeedingDictionary)
{
throw new InvalidOperationException("Dictionary is not needed");
}
adler.Update(buffer, index, count);
this.adler.Update(buffer, index, count);
if ((int)adler.Value != readAdler)
if ((int)this.adler.Value != this.readAdler)
{
throw new ImageFormatException("Wrong adler checksum");
}
adler.Reset();
outputWindow.CopyDict(buffer, index, count);
mode = DECODE_BLOCKS;
this.adler.Reset();
this.outputWindow.CopyDict(buffer, index, count);
this.mode = DECODE_BLOCKS;
}
/// <summary>
@ -616,7 +636,7 @@
/// </param>
public void SetInput(byte[] buffer)
{
SetInput(buffer, 0, buffer.Length);
this.SetInput(buffer, 0, buffer.Length);
}
/// <summary>
@ -640,8 +660,8 @@
/// </exception>
public void SetInput(byte[] buffer, int index, int count)
{
input.SetInput(buffer, index, count);
totalIn += (long)count;
this.input.SetInput(buffer, index, count);
this.totalIn += (long)count;
}
/// <summary>
@ -670,7 +690,7 @@
throw new ArgumentNullException(nameof(buffer));
}
return Inflate(buffer, 0, buffer.Length);
return this.Inflate(buffer, 0, buffer.Length);
}
/// <summary>
@ -709,20 +729,12 @@
if (count < 0)
{
#if NETCF_1_0
throw new ArgumentOutOfRangeException("count");
#else
throw new ArgumentOutOfRangeException(nameof(count), "count cannot be negative");
#endif
}
if (offset < 0)
{
#if NETCF_1_0
throw new ArgumentOutOfRangeException("offset");
#else
throw new ArgumentOutOfRangeException(nameof(offset), "offset cannot be negative");
#endif
}
if (offset + count > buffer.Length)
@ -733,10 +745,11 @@
// Special case: count may be zero
if (count == 0)
{
if (!IsFinished)
if (!this.IsFinished)
{ // -jr- 08-Nov-2003 INFLATE_BUG fix..
Decode();
this.Decode();
}
return 0;
}
@ -744,22 +757,22 @@
do
{
if (mode != DECODE_CHKSUM)
if (this.mode != DECODE_CHKSUM)
{
/* Don't give away any output, if we are waiting for the
* checksum in the input stream.
*
* With this trick we have always:
* IsNeedingInput() and not IsFinished()
* implies more output can be produced.
*/
int more = outputWindow.CopyOutput(buffer, offset, count);
* checksum in the input stream.
*
* With this trick we have always:
* IsNeedingInput() and not IsFinished()
* implies more output can be produced.
*/
int more = this.outputWindow.CopyOutput(buffer, offset, count);
if (more > 0)
{
adler.Update(buffer, offset, more);
this.adler.Update(buffer, offset, more);
offset += more;
bytesCopied += more;
totalOut += (long)more;
this.totalOut += (long)more;
count -= more;
if (count == 0)
{
@ -767,45 +780,28 @@
}
}
}
} while (Decode() || ((outputWindow.GetAvailable() > 0) && (mode != DECODE_CHKSUM)));
}
while (this.Decode() || ((this.outputWindow.GetAvailable() > 0) && (this.mode != DECODE_CHKSUM)));
return bytesCopied;
}
/// <summary>
/// Returns true, if the input buffer is empty.
/// You should then call setInput().
/// You should then call setInput().
/// NOTE: This method also returns true when the stream is finished.
/// </summary>
public bool IsNeedingInput
{
get
{
return input.IsNeedingInput;
}
}
public bool IsNeedingInput => this.input.IsNeedingInput;
/// <summary>
/// Returns true, if a preset dictionary is needed to inflate the input.
/// </summary>
public bool IsNeedingDictionary
{
get
{
return mode == DECODE_DICT && neededBits == 0;
}
}
public bool IsNeedingDictionary => this.mode == DECODE_DICT && this.neededBits == 0;
/// <summary>
/// Returns true, if the inflater has finished. This means, that no
/// input is needed and no output can be produced.
/// </summary>
public bool IsFinished
{
get
{
return mode == FINISHED && outputWindow.GetAvailable() == 0;
}
}
public bool IsFinished => this.mode == FINISHED && this.outputWindow.GetAvailable() == 0;
/// <summary>
/// Gets the adler checksum. This is either the checksum of all
@ -816,13 +812,7 @@
/// <returns>
/// the adler checksum.
/// </returns>
public int Adler
{
get
{
return IsNeedingDictionary ? readAdler : (int)adler.Value;
}
}
public int Adler => this.IsNeedingDictionary ? this.readAdler : (int)this.adler.Value;
/// <summary>
/// Gets the total number of output bytes returned by Inflate().
@ -830,13 +820,7 @@
/// <returns>
/// the total number of output bytes.
/// </returns>
public long TotalOut
{
get
{
return totalOut;
}
}
public long TotalOut => this.totalOut;
/// <summary>
/// Gets the total number of processed compressed input bytes.
@ -844,13 +828,7 @@
/// <returns>
/// The total number of bytes of processed input bytes.
/// </returns>
public long TotalIn
{
get
{
return totalIn - (long)RemainingInput;
}
}
public long TotalIn => this.totalIn - (long)this.RemainingInput;
/// <summary>
/// Gets the number of unprocessed input bytes. Useful, if the end of the
@ -860,13 +838,6 @@
/// <returns>
/// The number of bytes of the input which have not been processed.
/// </returns>
public int RemainingInput
{
// TODO: This should be a long?
get
{
return input.AvailableBytes;
}
}
public int RemainingInput => this.input.AvailableBytes; // TODO: Should this be a long?
}
}

46
src/ImageProcessor/Formats/Png/Zlib/PendingBuffer.cs

@ -60,12 +60,6 @@
/// </param>
public void WriteByte(int value)
{
#if DebugDeflation
if (DeflaterConstants.DEBUGGING && (start != 0) )
{
throw new SharpZipBaseException("Debug check: start != 0");
}
#endif
buffer_[end++] = unchecked((byte)value);
}
@ -77,12 +71,6 @@
/// </param>
public void WriteShort(int value)
{
#if DebugDeflation
if (DeflaterConstants.DEBUGGING && (start != 0) )
{
throw new SharpZipBaseException("Debug check: start != 0");
}
#endif
buffer_[end++] = unchecked((byte)value);
buffer_[end++] = unchecked((byte)(value >> 8));
}
@ -93,12 +81,6 @@
/// <param name="value">The value to write.</param>
public void WriteInt(int value)
{
#if DebugDeflation
if (DeflaterConstants.DEBUGGING && (start != 0) )
{
throw new SharpZipBaseException("Debug check: start != 0");
}
#endif
buffer_[end++] = unchecked((byte)value);
buffer_[end++] = unchecked((byte)(value >> 8));
buffer_[end++] = unchecked((byte)(value >> 16));
@ -113,12 +95,6 @@
/// <param name="length">number of bytes to write</param>
public void WriteBlock(byte[] block, int offset, int length)
{
#if DebugDeflation
if (DeflaterConstants.DEBUGGING && (start != 0) )
{
throw new SharpZipBaseException("Debug check: start != 0");
}
#endif
System.Array.Copy(block, offset, buffer_, end, length);
end += length;
}
@ -139,12 +115,6 @@
/// </summary>
public void AlignToByte()
{
#if DebugDeflation
if (DeflaterConstants.DEBUGGING && (start != 0) )
{
throw new SharpZipBaseException("Debug check: start != 0");
}
#endif
if (bitCount > 0)
{
buffer_[end++] = unchecked((byte)bits);
@ -164,16 +134,6 @@
/// <param name="count">number of bits to write</param>
public void WriteBits(int b, int count)
{
#if DebugDeflation
if (DeflaterConstants.DEBUGGING && (start != 0) )
{
throw new SharpZipBaseException("Debug check: start != 0");
}
// if (DeflaterConstants.DEBUGGING) {
// //Console.WriteLine("writeBits("+b+","+count+")");
// }
#endif
bits |= (uint)(b << bitCount);
bitCount += count;
if (bitCount >= 16)
@ -191,12 +151,6 @@
/// <param name="s">value to write</param>
public void WriteShortMSB(int s)
{
#if DebugDeflation
if (DeflaterConstants.DEBUGGING && (start != 0) )
{
throw new SharpZipBaseException("Debug check: start != 0");
}
#endif
buffer_[end++] = unchecked((byte)(s >> 8));
buffer_[end++] = unchecked((byte)s);
}

2
src/ImageProcessor/Formats/Png/Zlib/README.md

@ -0,0 +1,2 @@
The contents of this folder have been copied from https://github.com/ygrenier/SharpZipLib.Portable
in order to allow the project to run the NET 4.6 portable classes.

1
src/ImageProcessor/ImageProcessor.csproj

@ -238,6 +238,7 @@
<ItemGroup>
<None Include="Formats\Gif\README.md" />
<None Include="Formats\Jpg\README.md" />
<None Include="Formats\Png\Zlib\README.md" />
<None Include="packages.config" />
<None Include="stylecop.json" />
</ItemGroup>

1
src/ImageProcessor/ImageProcessor.csproj.DotSettings

@ -16,5 +16,6 @@
<s:Boolean x:Key="/Default/CodeInspection/NamespaceProvider/NamespaceFoldersToSkip/=formats_005Cpng/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/CodeInspection/NamespaceProvider/NamespaceFoldersToSkip/=formats_005Cpng_005Czlib/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/CodeInspection/NamespaceProvider/NamespaceFoldersToSkip/=formats_005Cpng_005Czlib2/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/CodeInspection/NamespaceProvider/NamespaceFoldersToSkip/=formats_005Cpng_005Czlip2/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/CodeInspection/NamespaceProvider/NamespaceFoldersToSkip/=numerics/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/CodeInspection/NamespaceProvider/NamespaceFoldersToSkip/=samplers_005Cresamplers/@EntryIndexedValue">True</s:Boolean></wpf:ResourceDictionary>

5
tests/ImageProcessor.Tests/Processors/Formats/EncoderDecoderTests.cs

@ -17,6 +17,11 @@
Directory.CreateDirectory("Encoded");
}
foreach (FileInfo file in new DirectoryInfo("Encoded").GetFiles())
{
file.Delete();
}
foreach (string file in Files)
{
using (FileStream stream = File.OpenRead(file))

Loading…
Cancel
Save