前言:
今天項目發布上線,發布到正式環境驗證功能的時候忽然方向之前做的一個圖片合成的功能報錯了提示: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是否存在讀寫的權限(讓服務器管理員查了下果然是沒有權限的),把權限的讀寫權限開通后就一切正常了。