ID: 7001 - Final Image class
Posted by layonman98 on Thu Mar 11 14:13:56 UTC 2010.
Language csharp
public class PhotoHelper
{
internal static Image ResizeWithoutLosingProportion(Image img, int MaxWidth, int MaxHeight)
{
Image nImg = null;
if (img.Width > MaxWidth || img.Height > MaxHeight)
{
// Si la imágen NO es cuadrada
if (img.Width != img.Height)
{
// Si la imágen es 'a lo alto'
if (img.Width < img.Height)
{
double nHeight = MaxHeight;
double percent = ((img.Height - nHeight) * 100 / img.Height) / 100;
double nWidth = img.Width - (img.Width * percent);
nImg = ResizeImg((Bitmap)img, (int)nWidth, (int)nHeight);
}
// Si la imágen es 'a lo ancho'
else if (img.Width > img.Height)
{
double nWidth = MaxWidth;
double percent = ((img.Width - nWidth) * 100 / img.Width) / 100;
double nHeight = img.Height - (img.Height * percent);
nImg = ResizeImg((Bitmap)img, (int)nWidth, (int)nHeight);
}
}
// Si la imágen es cuadrada
else if (img.Width == img.Height)
{
var nWidth = 604;
var nHeight = 604;
nImg = ResizeImg((Bitmap)img, nWidth, nHeight);
}
}
else
{
nImg = img;
}
return nImg;
}
internal static Bitmap ResizeImg(Bitmap img, int nWidth, int nHeight)
{
var result = new Bitmap(nWidth, nHeight);
using (Graphics g = Graphics.FromImage((Image)result))
{
g.DrawImage( img, 0, 0, nWidth, nHeight );
}
return result;
}
internal static void AddWaterMark( Image img, Image watermark, WatermarkLocation dest )
{
Graphics g = Graphics.FromImage((Image)img);
Point point = new Point();
switch (dest)
{
case WatermarkLocation.UpperLeft:
point.X = 0;
point.Y = 0;
break;
case WatermarkLocation.UpperRight:
point.X = img.Width - watermark.Width;
point.Y = 0;
break;
case WatermarkLocation.LowerLeft:
point.X = 0;
point.Y = img.Height - watermark.Height;
break;
case WatermarkLocation.LowerRight:
point.X = img.Width - watermark.Width;
point.Y = img.Height - watermark.Height;
break;
default:
break;
}
g.DrawImage(watermark, point);
}
internal static ImageFormat GetImageFormat( string fileExtention )
{
ImageFormat imgFormat = null;
if ( string.Equals( fileExtention, "jpeg" ) || string.Equals( fileExtention, "jpg" ) )
imgFormat = ImageFormat.Jpeg;
else if ( string.Equals( fileExtention, "png" ) )
imgFormat = ImageFormat.Png;
else if ( string.Equals( fileExtention, "gif" ) )
imgFormat = ImageFormat.Gif;
else if ( string.Equals( fileExtention, "bmp" ) )
imgFormat = ImageFormat.Bmp;
return imgFormat;
}
}