i have following coding to resize image and than save it my virtual folder “vicpic/scimages”
if (FileUpload5.PostedFile != null)
{
if (FileUpload5.PostedFile.ContentLength > (1024 * 1024))
{
Label4.Text = "Upload status: The file has to be less than 1 MB. Please resize your photo and than upload it again.";
}
else
{
System.Drawing.Image imageToBeResized = System.Drawing.Image.FromStream(FileUpload5.PostedFile.InputStream);
int imageHeight = imageToBeResized.Height;
int imageWidth = imageToBeResized.Width;
int maxHeight = 660;
int maxWidth = 560;
imageHeight = (imageHeight * maxWidth) / imageWidth;
imageWidth = maxWidth;
if (imageHeight > maxHeight)
{
imageWidth = (imageWidth * maxHeight) / imageHeight;
imageHeight = maxHeight;
}
Bitmap bitmap = new Bitmap(imageToBeResized, imageWidth, imageHeight);
System.IO.MemoryStream stream = new MemoryStream();
// bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
stream.Position = 0;
byte[] image = new byte[stream.Length + 1];
stream.Read(image, 0, image.Length);
string FileName = Path.GetFileName(FileUpload5.PostedFile.FileName);
//Save files to disk
string extension = Path.GetExtension(FileUpload5.PostedFile.FileName);
//Path.Combine(Server.MapPath("~/vicpic/scimages"), imageName);
string imagename = DropDownList2.SelectedItem.Text + "4" + extension;
bitmap.Save(Server.MapPath("~/vicpic/scimages/") + imagename);
bitmap.Dispose();
imageToBeResized.Dispose();
GC.Collect();
try
{
con.Open();
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
con.Close();
con.Dispose();
Label4.Text = "Upload status:Successfully.";
}
}
}
but it shows A generic error occurred in GDI+
can anyone suggest where the problem is?
i want to save image in “vicpic/scimages” folder on my host server. it is virtual directory and i also have granted all the permission required for the directory.
I had the same issue. It appears that the memory stream that the object was created on has to be open at the time the object is saved. Not to duplicate code and text just take a look at this Q & A: A generic error occurred in GDI+, JPEG Image to MemoryStream
So instead of
bitmap.Save(Server.MapPath("~/vicpic/scimages/") + imagename);your code could look like this: