Basierend auf diesem MSDN Artikel habe ich eine Klasse geschrieben die wie File.Copy(source, target); funktioniert, jedoch bei wechselnder Endung eine Konvertierung vornimmt.
namespace ImageConversion
{
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
public class ImageConverter
{
///
/// Copies file from source to destination. If target path has different ending it converts the file.
///
///Existing source file with original ending and filetype.
///Non existing target file with same or different ending.
public static void Convert(string source, string target)
{
string sourceExtension = Path.GetExtension(source).ToLower();
string targetExtension = Path.GetExtension(target).ToLower();
if (sourceExtension == targetExtension)
{ //no conversion neccessary, just copy
File.Copy(source, target);
return;
}
// Load the image.
Image image = Image.FromFile(source);
if(targetExtension.Equals(".jpg") || targetExtension.Equals(".jpeg"))
{
// Save the image in JPEG format.
image.Save(target, ImageFormat.Jpeg);
}
else if (targetExtension.Equals(".gif"))
{
// Save the image in GIF format.
image.Save(target, ImageFormat.Gif);
}
else if (targetExtension.Equals(".png"))
{
// Save the image in PNG format.
image.Save(target, ImageFormat.Png);
}
else if (targetExtension.Equals(".bmp"))
{
// Save the image in PNG format.
image.Save(target, ImageFormat.Bmp);
}
else if (targetExtension.Equals(".tiff"))
{
// Save the image in PNG format.
image.Save(target, ImageFormat.Tiff);
}
else
{
throw new Exception("Unknown target file type!");
}
}
}
}
Verwendung:
ImageConverter.Convert(sourcePath, targetPath);

Schreibe einen Kommentar