In this asp.net web programming tutorial we will learn that how we can upload an image from our computer to a web server where our website is hosted.
see the below code just copy and paste in your .aspx.cs file.
see the below code just copy and paste in your .aspx.cs file.
protected void btn_upload_Click(object sender, EventArgs e) { imageflag = 1; if (!FileUpload_image.HasFile) { Alert.Show("No file for uploading"); return; } if (FileUpload_image.HasFile) { //string imagetype = FileUpload_image.PostedFile.ContentType; string[] acceptedTypes = new string[] { "image/bmp", "image/jpeg", "image/tiff", "image/gif", "image/png" }; if (!acceptedTypes.Contains(FileUpload_image.PostedFile.ContentType)) { Alert.Show("This is not image file"); return; } Bitmap image = ResizeImage(FileUpload_image.PostedFile.InputStream, 84, 118); string imagename = Guid.NewGuid().ToString(); image.Save(Server.MapPath("~/Employee Pictures/") + imagename + ".jpg", System.Drawing.Imaging.ImageFormat.Jpeg); Img_Employee.ImageUrl = "~/Employee Pictures/" + imagename + ".jpg"; image_path = "~/Employee Pictures/" + imagename + ".jpg"; } } private Bitmap ResizeImage(Stream streamImage, int maxWidth, int maxHeight) { Bitmap originalImage = new Bitmap(streamImage); int newWidth = originalImage.Width; int newHeight = originalImage.Height; double aspectRatio = (double)originalImage.Width / (double)originalImage.Height; if (aspectRatio <= 1 && originalImage.Width > maxWidth) { newWidth = maxWidth; newHeight = (int)Math.Round(newWidth / aspectRatio); } else if (aspectRatio > 1 && originalImage.Height > maxHeight) { newHeight = maxHeight; newWidth = (int)Math.Round(newHeight * aspectRatio); } return new Bitmap(originalImage, newWidth, newHeight); }
Tags:
asp.net