21 March 2013

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();

No comments:

Post a Comment