Asp.net blogs

Friday 5 July 2013

Upload Image File according to Dimensions choice i.e. Height and Width :

Upload Image File according to Dimensions choice i.e. Height and Width : In which whenever you will upload a image then you can set it with any dimensions with the following C# code as shown below :

 protected void btnSave_Click(object sender, EventArgs e)
        {
            if (imageUpload.HasFile)
            {
                string extension = Path.GetExtension(imageUpload.PostedFile.FileName);
                Boolean flag = checkext(extension);
                if (flag == true)
                {
                    String imagepath = uploadImagess(imageUpload.PostedFile, Convert.ToInt32(356), Convert.ToInt32(1600));
                    Initialize();
                    obj.InsertBannerLinks(imagepath, "True");
                   lblmsz.Text = "Image Saved Successfully.";
                }
                else
                {

                    lblmsz.Text = "Invalid file extension.";
                }
            }
            else
            {
                lblmsz.Text = "Please Upload Image";
            }
        }


 public Boolean checkext(String ext)
        {
            String[] exts = {".bmp", ".jpg", ".jpeg", ".gif", ".tif", ".png"};
            if (exts.Contains(ext.ToLower()))
            {
                return true;
            }
            else
            {
                return false;
            }
        }
 private String uploadImagess(HttpPostedFile fil, int height, int width)
        {
            string now = DateTime.Now.ToString("MM-dd-yyyy");
            string DateFormat = now.Replace('-', '_');
            string now2 = DateTime.Now.ToString("HH:mm");
            string DateFormat2 = now2.Replace(':', '_');
            String fulldate = DateFormat + DateFormat2;
         
            String Name = fulldate + fil.FileName;
            Byte[] fileBinary = GetPictureBitss(fil.InputStream, fil.ContentLength);
            MemoryStream stream = new MemoryStream(fileBinary);
            Bitmap b = new Bitmap(stream);
            Bitmap s = new Bitmap(stream);
            Size newsize = new Size();
            newsize.Height = height;
            newsize.Width = width;
            Bitmap newBitMap = new Bitmap(newsize.Width, newsize.Height);
            Graphics g = Graphics.FromImage(newBitMap);
            g.DrawImage(b, 0, 0, newsize.Width, newsize.Height);
            newBitMap.Save(Server.MapPath("~/BannerImage/") + Name, ImageFormat.Jpeg);
            newsize.Height = 56;
            newsize.Width = 56;
            newBitMap.Dispose();
            s.Dispose();
            b.Dispose();
            return Name;
        }

 private Byte[] GetPictureBitss(Stream fs, int size)
        {
            Byte[] img = new Byte[size];
            fs.Read(img, 0, size);
            return img;
        }

No comments:

Post a Comment