【排查解決】System.Runtime.InteropServices.ExternalException (0x80004005): GDI+ 中發生一般性錯誤

追逐時光者發表於2021-06-04

前言:

  今天專案釋出上線,釋出到正式環境驗證功能的時候忽然方向之前做的一個圖片合成的功能報錯了提示:System.Runtime.InteropServices.ExternalException (0x80004005): GDI+ 中發生一般性錯誤。也就是說應用的System.Drawing中的Bitmap的這個類中的屬性出了問題,這到底是什麼問題呢?首先我本地開發,測試環境都可以正常的,為什麼已釋出到正式環境就有問題了呢,到底是環境問題還是配置許可權的問題呢?

程式碼如下:

        /// <summary>
        /// 合成圖片
        /// </summary>
        /// <param name="backgroundImage">背景圖</param>
        /// <param name="qrCodeImg">二維碼圖片</param>
        /// <param name="savePhysicalPath">圖片存放物理路徑</param>
        /// <param name="xDeviation">繪製影像X軸偏差</param>
        /// <param name="yDeviation">繪製影像Y軸偏差</param>
        /// <param name="width">繪製影像寬</param>
        /// <param name="height">繪製影像高</param>
        /// <returns></returns>
        public string CompositePicture(Image backgroundImage, Image qrCodeImg, string savePhysicalPath, int xDeviation = 0, int yDeviation = 0, int width = 0, int height = 0)
        {
            Bitmap bitmap = new Bitmap(backgroundImage.Width, backgroundImage.Height);
            Graphics graphics = Graphics.FromImage(bitmap);//繪圖
            graphics.Clear(Color.White);
            SolidBrush surush = new SolidBrush(Color.White);
            graphics.DrawImage(backgroundImage, 0, 0, backgroundImage.Width, backgroundImage.Height);
            graphics.DrawImage(qrCodeImg, xDeviation, yDeviation, width, height);
            GC.Collect();//垃圾清理

            string compositePictureUrl = savePhysicalPath + Guid.NewGuid().ToString() + ".jpg";
            //合成圖片儲存
            bitmap.Save(compositePictureUrl, System.Drawing.Imaging.ImageFormat.Jpeg);

            return compositePictureUrl;
        }

解決方案:

1、首先我排除了一下線上伺服器是否存在savePhysicalPath圖片存放的物理路徑(我釋出合成的圖片儲存的物理物理為/Content/Image)檢視確實存在,因為之前在程式中寫過判斷資料夾是否存在不存在建立資料夾的邏輯。

            if (!Directory.Exists(savePhysicalPath))
            {
                Directory.CreateDirectory(savePhysicalPath);
            }

2、判斷檔案Image是否存在讀寫的許可權(讓伺服器管理員查了下果然是沒有許可權的),把許可權的讀寫許可權開通後就一切正常了。

 

相關文章