Loading and Saving Images (Console)
Let’s start very simple: we want a Console app that takes two arguments:
- Image input path
- Image output path
The app loads the image given as the first argument and saves to the path in the second argument:
-
Add namespace (we need the Stemmer.Cvb.dll for this):
using Stemmer.Cvb;
-
Load the input image via
Image.FromFile
factory method:var image = Image.FromFile(args[0]);
(we assume that the user provided the input in
args[0]
) -
Save the image:
image.Save(args[1]);
(we assume that the user provided the output in
args[1]
)
:cvb: determines the file format based on the file’s extension (.bmp, .jpg, .png,…).
The full app with (simple) error handling.
using Stemmer.Cvb;
using System;
using System.IO;
namespace CvbPlayground
{
class Program
{
static void Main(string[] args)
{
if (args.Length != 2)
{
PrintHelp();
return;
}
try
{
using (var inputImage = Image.FromFile(args[0]))
{
inputImage.Save(args[1]);
Console.WriteLine("Convert");
Console.WriteLine(" " + Path.GetFullPath(args[0]));
Console.WriteLine("->");
Console.WriteLine(" " + Path.GetFullPath(args[1]));
}
}
catch (IOException ex)
{
Console.WriteLine(ex);
}
}
private static void PrintHelp()
{
Console.WriteLine("Usage: " + AppName + " <input> <output>");
Console.WriteLine();
Console.WriteLine("<input> Path to input file to convert.");
Console.WriteLine("<output> Path to output file to convert.");
}
private static string AppName
{
get
{
return Path.GetFileNameWithoutExtension(typeof(Program).Assembly.Location);
}
}
}
}
If you read so far , you get a little bonus: perhaps you have seen the using (var inputImage
… block. :cvb: Image
s are IDisposable
types. That means that you can free their resources (memory in this case) immediatly via image.Dispose()
. A using
block does that always when the program exits its scope. Even if exceptions occur. So we use the image only as long as we actually need it.