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));
4

2 回答 2

3

这可能是由于文件本身不存在。

您可以使用检查该文件是否存在

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

或者,您可以翻转此代码并提醒用户

if (!File.Exists(fileName)
{
   //Throws exception/Alert user here
}
于 2012-08-02T08:31:24.200 回答
0

对于 winforms ChrisBint 发布的内容也是有效且正确的。此外,请务必将资源/图像设置为可用于您的可执行文件。

例如复制到输出:始终复制

在此处输入图像描述

于 2013-12-20T18:20:24.447 回答