Tuesday, February 23, 2010

How to upload and resizing image in asp.net?

Here is the code:
protected void btnUpload_Click(object sender, EventArgs e)
    {
        if (flUpImage.HasFile)
        {
            picName = flUpImage.FileName;
            string SavePath = Server.MapPath("~/Coach/Data/" + Convert.ToString(iPlayConstant._PLAYER_ID) + "/");
            DirectoryInfo di = new DirectoryInfo(SavePath);
            if (!di.Exists)
            {
                di.Create();
                SetPermissions(SavePath);
            }
            string LocalPath = Server.MapPath("~/Coach/Data/" + Convert.ToString(iPlayConstant._PLAYER_ID) + "/Profile.gif");
            flUpImage.SaveAs(LocalPath);
            System.Drawing.Image imgSaved = System.Drawing.Image.FromFile(LocalPath);
            System.Drawing.Image imgCroped;
            imgCroped = ImageResize(imgSaved, 250, 250);//pass the height and width value to create thumbnail picture
            imgProfile.Width = imgCroped.Width;
            imgProfile.Height = imgCroped.Height;
            imgSaved.Dispose();
            imgCroped.Save(LocalPath);
            imgCroped.Dispose();
            imgProfile.Src = "~/Coach/Data/" + Convert.ToString(iPlayConstant._PLAYER_ID) + "/Profile.gif";
        }
    }


    protected static System.Drawing.Image ImageResize(
        System.Drawing.Image imgPhoto, int dWidth, int dHeight)
    {
        int sourceWidth = imgPhoto.Width;
        int sourceHeight = imgPhoto.Height;
        int destWidth = dWidth;
        int destHeight = dHeight;
        int sourceX = 0;
        int sourceY = 0;
        int destX = 0;
        int destY = 0;
        float percent = 0;

        if (sourceHeight > sourceWidth)
        {
            percent = (float)sourceWidth / (float)sourceHeight;
            destWidth = (int)(percent * destWidth);
        }
        else
        {
            percent = (float)sourceHeight / (float)sourceWidth;
            destHeight = (int)(percent * destHeight);
        }
        if (destWidth > destHeight)
        {
            percent = (float)sourceHeight / (float)sourceWidth;
            destWidth = (int)(percent * destWidth);
        }
        System.Drawing.Bitmap bmPhoto = new Bitmap(destWidth, destHeight, PixelFormat.Format24bppRgb);
        bmPhoto.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution);
        Graphics grPhoto = Graphics.FromImage(bmPhoto);
        grPhoto.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
        grPhoto.DrawImage(imgPhoto,
        new Rectangle(destX, destY, destWidth, destHeight),
        new Rectangle(sourceX, sourceY, sourceWidth, sourceHeight),
        GraphicsUnit.Pixel);
        grPhoto.Dispose();
        return bmPhoto;
    }

No comments:

Post a Comment