You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

尝试替换文件夹图片时出现GDI+通用错误,本地运行正常

解决替换图片时GDI+通用错误(本地正常,部署后报错)

核心原因及修复方法

  • 服务器文件夹权限不足
    本地运行时用的是你的个人用户权限,部署到服务器后,应用程序池的身份没有~/img/bg-img/文件夹的写入权限。直接找到服务器上对应文件夹,给应用程序池用户(比如IIS AppPool\你的应用池名称)添加写入和修改权限即可。

  • 目标文件被占用
    服务器上的bgimg1.jpg可能被其他进程锁定(比如之前的请求没释放资源,或者图片被浏览器缓存占用)。保存前先解除文件占用:

    string savePath = Server.MapPath("~/img/bg-img/bgimg1.jpg");
    if (File.Exists(savePath))
    {
        File.SetAttributes(savePath, FileAttributes.Normal);
    }
    target.Save(savePath);
    
  • GDI+资源未释放
    原代码未手动释放Bitmap、Graphics这些对象,长期运行会导致资源泄漏触发错误。用using语句自动释放资源,优化后的完整代码:

    if (FuBannerImg2.HasFile)
    {
        int width = 1920;
        int height = 1280;
        using (Stream stream = FuBannerImg2.PostedFile.InputStream)
        using (Bitmap image = new Bitmap(stream))
        using (Bitmap target = new Bitmap(width, height))
        using (Graphics graphic = Graphics.FromImage(target))
        {
            graphic.DrawImage(image, 0, 0, width, height);
            string savePath = Server.MapPath("~/img/bg-img/bgimg1.jpg");
            // 确保目标文件夹存在
            string folderPath = Path.GetDirectoryName(savePath);
            if (!Directory.Exists(folderPath))
            {
                Directory.CreateDirectory(folderPath);
            }
            if (File.Exists(savePath))
            {
                File.SetAttributes(savePath, FileAttributes.Normal);
            }
            target.Save(savePath);
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "clientScript", "alert('Image uploaded Successfully')", true);
            fillhome();
        }
    }
    
  • 目标文件夹不存在
    服务器上可能未自动创建~/img/bg-img/文件夹,提前判断并创建可避免路径错误。

内容的提问来源于stack exchange,提问作者Jackwin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 23:54:06