Wednesday, March 20, 2013

Image Resize in C# code behind

using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;

///
/// Resizes any images passed to it and created a thumbnail if wanted.
/// Expects: string, int, int, bool, stream.
///

public class ImageResizer
{
    public static void Resize(string filePath, int maxWidth, int maxHeight, Stream buffer)
    {
        Image image = Image.FromStream(buffer);

        float origimgWidth = image.PhysicalDimension.Width;
        float origimgHeight = image.PhysicalDimension.Height;
        float imgWidth = origimgWidth, imgHeight = origimgHeight;
        float imgSize, imgResize = 0;

        //resize by width
        if ((imgWidth > imgHeight))
        {
            imgSize = imgWidth;
            imgResize = imgSize <= maxWidth ? (float)1.0 : maxWidth / imgSize;
        }
        else
            //resize image based on height it the height and width are the same or if the height is greater than the width
            if ((imgHeight > imgWidth))
            {
                imgSize = imgHeight;
                imgResize = imgSize <= maxWidth ? (float)1.0 : maxHeight / imgSize;
            }
            else
                if ((imgHeight == imgWidth))
                {
                    imgSize = imgHeight;
                    imgResize = imgSize <= maxWidth ? (float)1.0 : maxHeight / imgSize;
                }

        imgWidth *= imgResize;
        imgHeight *= imgResize;

        //save the image using the dimensions gathered above
        ImageCodecInfo codec = ImageCodecInfo.GetImageEncoders()[1];
        EncoderParameters eParams = new EncoderParameters(1);
        eParams.Param[0] = new EncoderParameter(Encoder.Quality, 80L);
        Bitmap bmp = new Bitmap((int)imgWidth, (int)imgHeight);
        Graphics gr = Graphics.FromImage(bmp);
        gr.SmoothingMode = SmoothingMode.HighQuality;
        gr.CompositingQuality = CompositingQuality.HighQuality;
        gr.InterpolationMode = InterpolationMode.High;
        Rectangle rectDestination = new Rectangle(0, 0, (int)imgWidth, (int)imgHeight);
        gr.DrawImage(image, rectDestination, 0, 0, origimgWidth, origimgHeight, GraphicsUnit.Pixel);
        bmp.Save(filePath, codec, eParams);
        bmp.Dispose();
        image.Dispose();
    }
}

1 comment:


  1. Online image resize is the most comprehensive free image resizer tool online.now you can resize images and resize photosOnline.

    ReplyDelete

fill in blanks

ALL Reading Blanks: Special All approaches aim to increase blood flow to areas of tension and to release painful knots opt1 muscle kn...