Skip to main content
 首页 » 编程设计

c#之将图像保存到 ASP.NET 服务器上的虚拟文件夹时获取 "A generic error occurred in GDI+"

2024年02月20日12虾米哥

我有以下代码来调整图像大小并将其保存在我的虚拟文件夹“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."; 
 
            } 
        } 
 
    } 

但它显示 GDI+ 中发生一般错误

谁能指出问题出在哪里?

我想将图像保存在我的主机服务器上的“vicpic/scimages”文件夹中。它是虚拟目录,我也已授予该目录所需的所有权限。

请您参考如下方法:

我遇到了同样的问题。看起来创建对象的内存流必须在保存对象时打开。不要重复代码和文本,只需看看这个问答:A generic error occurred in GDI+, JPEG Image to MemoryStream

因此,代替 bitmap.Save(Server.MapPath("~/vicpic/scimages/") + imagename);,您的代码可能如下所示:

using (var m = new MemoryStream()) 
{ 
       bitmap.Save(m, ImageFormat.Jpeg); 
       var img = Image.FromStream(m); 
       img.Save(Server.MapPath("~/vicpic/scimages/") + imagename); 
}