Change ratio of an image in C#

public static string ChangeImageProportion(string strImgPath, string strImgOutputPath, int iWidth, int iHeight)
{
    try
    {
        //Comprueba la extensión
        //if (Path.GetExtension(strImgPath).ToLower() != ".jpg")
        //{
        //    throw new Exception("El fichero debe estar en formato JPG. (" + strImgPath + ")");
        //}

        //Lee el fichero en un stream
        Stream mystream = null;

        if (strImgPath.StartsWith("http"))
        {
            HttpWebRequest wreq = (HttpWebRequest)WebRequest.Create(strImgPath);
            HttpWebResponse wresp = (HttpWebResponse)wreq.GetResponse();
            mystream = wresp.GetResponseStream();
        }
        else
            mystream = File.OpenRead(strImgPath);

        // Cargo la imágen
        Bitmap source = new Bitmap(mystream);

        int _targetWidth = source.Width;
        int _targetHeight = source.Height;

        /*** Calculo de las proporciones finales ***/
        double _relation = ((double)source.Width) / ((double)source.Height);
        double _canvasRelation = ((double)iWidth) / ((double)iHeight);

        if (_relation > _canvasRelation)
        {
            // El ancho es el lado grande, hay que aumentar el alto
            _targetHeight = iHeight * source.Width / iWidth;
        }
        else if (_relation < _canvasRelation)
        {
            // El alto es el lado grande, hay que aumentar el ancho
            _targetWidth = iWidth * source.Height / iHeight;
        }

        // Ahora miro el desfase
        int iTop = (_targetHeight - source.Height) / 2;
        int iLeft = (_targetWidth - source.Width) / 2;

        // La nueva
        Bitmap target = new Bitmap(_targetWidth, _targetHeight);
        Graphics g = Graphics.FromImage(target);
        g.CompositingQuality = CompositingQuality.HighQuality;

        Color cW = Color.White;
        Brush brush = new SolidBrush(cW);
        g.FillRectangle(brush, 0, 0, _targetWidth, _targetHeight);
        g.DrawImage(source,
                    new Rectangle(iLeft, iTop, source.Width, source.Height),
                    0,
                    0,
                    source.Width,
                    source.Height,
                    GraphicsUnit.Pixel);

        // We will store the correct image codec in this object
        ImageCodecInfo ici = GetEncoderInfo("image/jpeg"); ;
        // This will specify the image quality to the encoder
        EncoderParameter epQuality = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 99L);
        // Store the quality parameter in the list of encoder parameters
        EncoderParameters eps = new EncoderParameters(1);
        eps.Param[0] = epQuality;

        // Genero un nuevo nombre de fichero
        //strImgPath = Path.Combine(Path.GetDirectoryName(strImgPath),Guid.NewGuid().ToString() + ".jpg");

        target.Save(strImgOutputPath, ici, eps);

        source.Dispose();
        target.Dispose();
        g.Dispose();

        return strImgPath;
    }
    catch
    {
        throw;
    }
}

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *

Este sitio usa Akismet para reducir el spam. Aprende cómo se procesan los datos de tus comentarios.