In this web programming tutorial we will learn that how we can upload a picture or photo in asp.net using c#. just copy and paste below code in you .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("~/Pictures/") + imagename + ".jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
Img_Employee.ImageUrl = "~/Pictures/" + imagename + ".jpg";
image_path = "~/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