2012-08-02 95 views
0

我試圖直接從包含文件名和路徑的字符串創建位圖時遇到錯誤。位圖參數無效

我的代碼如下描述:

if (!string.IsNullOrEmpty(Request.QueryString["imagename"])) 
    { 
     string Image = Request.QueryString["imagename"]; 

     Bitmap originalBMP = new Bitmap(Server.MapPath(@"UserImages/" + Image)); 

     // Calculate the new image dimensions 
     int origWidth = originalBMP.Width; 
     int origHeight = originalBMP.Height; 
     int sngRatio = origWidth/origHeight; 
     int newWidth = 50; 
     int newHeight = newWidth/sngRatio; 

     // Create a new bitmap which will hold the previous resized bitmap 
     Bitmap newBMP = new Bitmap(originalBMP, newWidth, newHeight); 

     // Create a graphic based on the new bitmap 
     Graphics oGraphics = Graphics.FromImage(newBMP); 
     // Set the properties for the new graphic file 
     oGraphics.SmoothingMode = SmoothingMode.AntiAlias; oGraphics.InterpolationMode = InterpolationMode.HighQualityBicubic; 

     // Draw the new graphic based on the resized bitmap 
     oGraphics.DrawImage(originalBMP, 0, 0, newWidth, newHeight); 
     // Save the new graphic file to the server 

     Response.ContentType = "image/PNG"; 
     newBMP.Save(Response.OutputStream, ImageFormat.Png); 

     originalBMP.Dispose(); 
     newBMP.Dispose(); 
     oGraphics.Dispose(); 
    } 

但是,下面的代碼產生錯誤參數無效:

Bitmap originalBMP = new Bitmap(Server.MapPath(@"UserImages/" + Image)); 
+0

是否文件中存在?路徑是否正確? – ChrisBint 2012-08-02 08:14:11

+0

您是否調試過要獲取要加載的文件名,然後檢查該文件是否存在? – 2012-08-02 08:14:27

+0

不應該是'Server.MapPath(@「/ UserImages /」+ Image));'?沒有正斜槓,它將'UserImages'視爲文件而不是目錄 – dtsg 2012-08-02 08:16:14

回答

3

這可能是下降的事實,文件本身不存在。

您可以檢查使用

var fileName =Server.MapPath(@"UserImages/" + Image); 
if (File.Exists(fileName) 
{ 
    //Existing code here 
} 

或者該文件的存在,你可以翻轉這個代碼,並提醒用戶

if (!File.Exists(fileName) 
{ 
    //Throws exception/Alert user here 
} 
0

對於的WinForms什麼ChrisBint發佈也是有效和恰當的。另外,請務必將資源/映像設置爲可用於您的可執行文件。

例如複製到輸出:始終複製

enter image description here