2012-08-02 6 views
0

Je fais face à une erreur lors de la tentative de créer une image bitmap directement à partir d'une chaîne qui contient le nom de fichier et le chemin.Bitmap Paramètre non valide

Mon code est décrit ci-dessous:

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(); 
    } 

Mais le code suivant est produit une erreur qui paramètre est incorrect:

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

Est-ce que le fichier existe? Le chemin est-il correct? – ChrisBint

+0

avez-vous débogué pour obtenir le nom du fichier que vous essayez de charger, puis vérifié pour voir si le fichier existe? –

+0

devrait-il pas être 'Server.MapPath (@ "/ userimages /" + image));'? Sans la barre oblique il traite 'UserImages' comme un fichier et non un répertoire – dtsg

Répondre

3

Il est sans doute au fait que le fichier lui-même ne exister.

Vous pouvez vérifier l'existence de ce fichier en utilisant

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

Sinon, vous pouvez retourner ce code et alerter l'utilisateur

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

Pour WinForms Qu'est-ce que ChrisBint affichés sont également valables et bon. En outre assurez-vous de définir la ressource/image disponible pour votre exécutable.

par exemple Copie à la sortie: Copiez toujours

enter image description here

Questions connexes