Skip to content

Instantly share code, notes, and snippets.

@morbidcamel101
Last active August 29, 2015 14:09
Show Gist options
  • Save morbidcamel101/4b2b4fdb1748803b44a2 to your computer and use it in GitHub Desktop.
Save morbidcamel101/4b2b4fdb1748803b44a2 to your computer and use it in GitHub Desktop.
.NET Signature Stream Utility class
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Signatures
{
/// <summary>
/// Line drawing commands as generated by the Signature Pad JSON export option.
/// </summary>
public struct SignatureLine
{
public int lx;
public int ly;
public int mx;
public int my;
}
public static class SignatureUtil
{
public static void WriteSignature(Stream outputStream, SignatureLine[] lines)
{
BinaryWriter writer = new BinaryWriter(outputStream);
writer.Write(lines.Length); // First int is the length of the line segments
for (int i = 0; i < lines.Length; i++)
{
var line = lines[i];
writer.Write(line.lx);
writer.Write(line.ly);
writer.Write(line.mx);
writer.Write(line.my);
}
writer.Flush();
}
public static SignatureLine[] ReadSignature(Stream inputStream)
{
int index = 0;
BinaryReader reader = new BinaryReader(inputStream);
inputStream.Seek(0, SeekOrigin.Begin);
int length = reader.ReadInt32();
var lines = new SignatureLine[length];
byte mode = 0;
int val;
while (inputStream.Position < inputStream.Length)
{
val = reader.ReadInt32();
switch (mode)
{
case 0:
lines[index].lx = val;
break;
case 1:
lines[index].ly = val;
break;
case 2:
lines[index].mx = val;
break;
case 3:
lines[index].my = val;
break;
}
mode = (byte)(((int)mode+1) % 4);
if (mode == 0)
index++;
}
return lines;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment