Aquest fragment de C# converteix una imatge a format JPG/GIF/PNG/BMP i amb una opció de definir una mida màxima, de manera que si és més gran, no sobrepasse aquestes dimensions, canviant la mida però mantenint l'aspecte.
using System.Drawing;
using System.Drawing.Imaging;
//variables
string file_src="C:\users\paco\imatge_original.jpg"; //conté la ruta de l'arxiu a convertir (IMATGE ORIGINAL)
int maxWidth = 800; //màxima amplada
int maxHeight = 600; //màxima alçada
Imageformat format = ImageFormat.Jpeg; //format de destinació (jpg, gif, bmp, png, ...)
string folder_dest="C:\users\paco\imatges_convertides";
string file_dest; //ruta de l'arxiu de destinació
file_dest = Path.Combine(folder_dest,Path.GetFileNameWithoutExtension(file_src)+format.ToString().ToLower()); //genera la ruta de l'arxiu de destinació a partir del nom original i del format convertit (opcional)
Image img = Image.FromFile(file_src);
if (img.Width > maxWidth || img.Height > maxHeight))
{
//correcció guarra per no usar el thumbnail intern de jpg
img.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);
img.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);
int newWidth = img.Width;
int newHeight = img.Height;
if (newWidth > maxWidth) //restringir l'ample
{
newWidth = maxWidth;
newHeight = (int)((float)maxWidth / (float)img.Width * (float)img.Height);
}
if (newHeight > maxHeight) //restringir l'alçada
{
newWidth = (int)((float)maxHeight / (float)newHeight * (float)newWidth);
newHeight = maxHeight;
}
System.Drawing.Image newImg = img.GetThumbnailImage(newWidth, newHeight, null, IntPtr.Zero);
newImg.Save(file_dest, format);
newImg.Dispose();
}
else
{
img.Save(file_dest, format);
}
img.Dispose();