ID: 6001 - Redimensionar una imagen guardando las proporciones dadas para los valores máximos que pueda adoptar
Posted by layonman98 on Mon Mar 08 20:35:17 UTC 2010. Language csharp

Bitmap ResizeWithoutLosingProportion( Image img, int MaxWidth, int MaxHeight )
{
	Image nImg = null;
	// Si la imágen sobrepasa el tamaño máximo
	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 );
		}
	}
	return nImg;
}

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;
}