21 March 2013

C# - Convert an SVG path to a GraphicsPath

The following algorithm takes the data string of an SVG path and converts it to a GDI+ GraphicsPath.
char command = ' ';
int[] args = null;
Point initPoint = new Point(); //Initial point of the subpath
Point endPoint = new Point(); //End point of the (previous) command
Point currentPoint = new Point(); //Current point of the command
Point point = new Point(); //Parsing variable
GraphicsPath path = new GraphicsPath();
List points = new List();

var functions = Regex.Split(data, @"(?=[A-Za-z])").Where(c => c.HasValue());
foreach (string function in functions) {
  command = function[0];
  args = Regex.Split(function.Remove(0, 1), @"[\s,]|(?=-)").Where(c => c.HasValue()).Select(c => c.ToInt()).ToArray();
  switch (command) {
    case 'M':
    case 'm': //Open subpath
      initPoint = new Point {
        X = (char.IsUpper(command) ? translation.X : currentPoint.X) + args[0] * scale.X,
        Y = (char.IsUpper(command) ? translation.Y : currentPoint.Y) + args[1] * scale.Y
      };
      endPoint = initPoint;
      currentPoint = initPoint;
      break;
    case 'Z':
    case 'z':
      path.CloseFigure();
      currentPoint = initPoint; //Init point becomes the current point
      break;
    case 'C':
    case 'c':
      points.Clear();
      points.Add(endPoint);
      int n = 0;
      for (int i = 0; i < args.Length; i += 2) {
        point = new Point {
          X = (char.IsUpper(command) ? translation.X : currentPoint.X) + args[i] * scale.X,
          Y = (char.IsUpper(command) ? translation.Y : currentPoint.Y) + args[i + 1] * scale.Y
        };
        points.Add(point);
        if (++n >= 3) { //Not a control point
          currentPoint = point;
          endPoint = point;
          n = 0;
        }
      }
      path.AddBeziers(points.ToArray());
      break;
    case 'L':
    case 'l':
      points.Clear();
      points.Add(endPoint);
      for (int i = 0; i < args.Length; i += 2) {
        point = new Point {
          X = (char.IsUpper(command) ? translation.X : currentPoint.X) + args[i] * scale.X,
          Y = (char.IsUpper(command) ? translation.Y : currentPoint.Y) + args[i + 1] * scale.Y
        };
        points.Add(point);
        currentPoint = point;
      }
      endPoint = currentPoint;
      path.AddLines(points.ToArray());
      break;
  }
}
Note that the points translation and scale were also taken from SVG and are used to displace the path points.

C# - Call Potrace and pass it a bitmap from code

The following snippet calls Potrace — a tool that converts raster images to vector images — and returns an SVG-string, without creating any files in between. I use this one in a drawing application I'm working on.
Process potrace = new Process {
  StartInfo = new ProcessStartInfo {
    FileName = "potrace.exe",
    Arguments = "-s -u 1", //SVG
    RedirectStandardInput = true,
    RedirectStandardOutput = true,
    RedirectStandardError = Program.IsDebug,
    UseShellExecute = false,
    CreateNoWindow = true,
    WindowStyle = ProcessWindowStyle.Hidden
  },
  EnableRaisingEvents = false
};

StringBuilder svgBuilder = new StringBuilder();
potrace.OutputDataReceived += (object sender2, DataReceivedEventArgs e2) => {
  svgBuilder.AppendLine(e2.Data);
};
if (Program.IsDebug) {
  potrace.ErrorDataReceived += (object sender2, DataReceivedEventArgs e2) => {
    Console.WriteLine("Error: " + e2.Data);
  };
}
potrace.Start();
potrace.BeginOutputReadLine();
if (Program.IsDebug) {
  potrace.BeginErrorReadLine();
}

BinaryWriter writer = new BinaryWriter(potrace.StandardInput.BaseStream);
bitmap.Save(writer.BaseStream, ImageFormat.Bmp);
potrace.StandardInput.WriteLine(); //Without this line the input to Potrace won't go through.
potrace.WaitForExit();

28 January 2013

Math - The split-and-merge algorithm

The split-and-merge or (Ramer-)Douglas-Peucker algorithm simplifies a list of points, removing those deemed redundant with respect to a given tolerance. You can read more about it here. I used it to reduce the input of the mouse cursor to a manageable set of points in a drawing application. Next is an implementation in C# in the form of an extension that acts on a List<Point>:

The entry method:

internal static List<Point> SplitAndMerge(this List<Point> points, double tolerance) {
  if (points == null || points.Count < 3) {
    return points;
  }
  else {
    List<int> indices = new List<int>();
    indices.Add(0);
    indices.Add(points.Count - 1);

    points.SplitAndMerge(0, points.Count - 1, tolerance, ref indices);

    List<point> result = new List<Point>();
    indices.Sort();
    foreach (int i in indices)
      result.Add(points[i]);
    return result;
  }
}

The private submethod that handles the recursive calls:

private static void SplitAndMerge(this List<Point> points, int indexFirst, int indexLast, double tolerance, ref List<int> indices) {
  double maxDist = 0d;
  int indexMaxDist = 0;
  double dist = 0d;

  for (int i = indexFirst; i < indexLast; i++) {
    dist = points[i].PerpendicularDistanceFrom(points[indexFirst], points[indexLast]);
    if (dist > maxDist) {
      maxDist = dist;
      indexMaxDist = i;
    }
  }

  if (maxDist > tolerance && indexMaxDist > 0) {
    indices.Add(indexMaxDist);
    points.SplitAndMerge(indexFirst, indexMaxDist, tolerance, ref indices);
    points.SplitAndMerge(indexMaxDist, indexLast, tolerance, ref indices);
  }
}

A helper method that calculates the distance between a point p to the line between a and b:

internal static double PerpendicularDistanceFrom(this Point p, Point a, Point b) {
  double area = Math.Abs(0.5d * (a.X * b.Y + b.X * p.Y + p.X * a.Y - b.X * a.Y - p.X * b.Y - a.X * p.Y));
  double bottom = Math.Sqrt((a.X - b.X) * (a.X - b.X) + (a.Y - b.Y) * (a.Y - b.Y));
  return area / bottom * 2d;
}

29 October 2012

C# extension - Parse to decimal regardless of regional settings

A problem that often comes up is that decimal numbers are wrongly parsed on different computers due to the regional settings. The following extensions are intended to ensure that a string is correctly parsed to a decimal, regardless of the decimal separator used by the system.

Parse

The first extension returns a string that can be correctly parsed to a decimal type.
/// <summary>
/// Parses a string that is supposed to be a decimal number in
/// such a way that it can be parsed to a decimal data type.
/// </summary>
/// <param name="source">The string to be parsed.</param>
/// <returns>A string that can be parsed to a decimal data type.</returns>
public static string ParseDecimalString(this string source) {
  if (!source.HasValue()) {
    return "0";
  }
  else {
    int indexLastSep = source.LastIndexOfAny(new char[] { '.', ',' });
    StringBuilder result = new StringBuilder();
    for (int i = 0; i < source.Length; i++) {
      if (char.IsDigit(source[i]))
        result.Append(source[i]);
      else if (i == indexLastSep)
        result.Append(CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator);
      else if (i == 0 && source[i] == '-')
        result.Append('-');
    }
    return result.ToString();
  }
}

Cast

The second extension does the casting. I separated this one from the parsing for reusability.
/// <summary>
/// Converts from string to decimal. Returns 0m on failure.
/// </summary>
/// <param name="source">The string.</param>
/// <returns>A decimal representing the string or 0m on failure.</returns>
public static decimal ToDecimal(this string source) {
  decimal result = 0m;
  decimal.TryParse(source.ParseDecimalString(), out result);
  return result;
}

25 October 2012

Extension - Strip a string

One day I wrote this convienient extension that removes letters, digits and/or symbols - as specified - from a string:
/// <summary>Removes characters of specified types.</summary>
/// <param name="source">The string to remove from.</param>
/// <param name="removeTypes">A string containing 'L' to remove letters, 'D' to remove digits and 'S' to remove symbols.</param>
/// <returns>A string containing the remaining characters.</returns>
public static string Strip(this string source, string removeTypes) {
  bool letters = !string.IsNullOrEmpty(removeTypes) && removeTypes.Contains('L');
  bool digits = !string.IsNullOrEmpty(removeTypes) && removeTypes.Contains('D');
  bool symbols = !string.IsNullOrEmpty(removeTypes) && removeTypes.Contains('S');

  StringBuilder result = new StringBuilder();
  if (!string.IsNullOrEmpty(source)) {
    foreach (char c in source) {
      if (char.IsLetter(c)) {
        if (!letters) result.Append(c);
      }
      else if (char.IsDigit(c)) {
        if (!digits) result.Append(c);
      }
      else {
        if (!symbols) result.Append(c);
      }
    }
  }
  return result.ToString();
}
Note that the line removeTypes.Contains(char) relies on System.Linq.

13 June 2012

SharePoint - Access the object model from a custom web service

I ran into a serious issue yesterday. I had built a custom web service to access a list on our SharePoint site, and everything seemed to work fine. But when I was not logged in, the site kept asking for my credentials and the line where I accessed the list threw a 401 - unauthorized. I tried to get to the list using SPContext, but even with RunWithElevatedPrivileges around it, it wouldn't work. The only thing I could do with SPContext however was get the GUID of the site and web that contained my list. So I got both of these and used them to gain access to my list like this:
SPSecurity.RunWithElevatedPrivileges(delegate() {
  using (SPSite spSite = new SPSite(new Guid("846ca17c-b8eb-4b04-8888-f5b7a1c6cfa3"))) {
    using (SPWeb web = spSite.OpenWeb(new Guid("14ba40e8-ee72-40fe-8b98-d1b1f72355aa"))) {
      list = web.Lists["Kalender"];
    }
  }
});
And surprise: this works!

31 May 2012

Math - Scaling a value

Sometimes you have this thing where you have two ranges, and you need to scale a value from the one to the other; e.g.:
Range 1: 0.....x.....100   x=50
Range 2: 0.....y.....500   y=?
Thus:
100 > 500
 50 >   ?
  x >   y

C# code

Thus, I want to know the value of y. I wrote this extension to get it:
internal static double Scale(this double value, double maxValue, double maxScale) {
  if (maxValue == 0 || maxScale == 0)
    return 0;
  else if (maxValue == maxScale)
    return value;
  else
    return value / (maxValue / maxScale);
}

result = 50.Scale(100, 500); //Result will be 250

Try it


if (max. value)equals (max. scale)
then (value)is (result)
...

See also

Interpolating a value